Je n'étais pas satisfait une réponse que je découvrais, je mélangé un peu et est venu avec cette (dans PowerShell 3.0+):
$output = try{your_command *>&1}catch{$_}
Avec cela, vous pouvez capturer toutes les erreurs et sortie qui sont générés en essayant d'utiliser your_command
.
Il capture des exceptions lorsque vous utilisez une commande inexistante:
PS C:\Users\jdgregson> $output = try{your_command *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
your_command : The term 'your_command' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:15
+ $output = try{your_command 2>&1}catch{$_}
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (your_command:String) [], Comman
dNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\jdgregson>
Il attrape des exceptions lorsque vous passez des arguments non valides à une commande existante:
PS C:\Users\jdgregson> $output = try{cat C:\invalid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
cat : Cannot find path 'C:\invalid-path.txt' because it does not exist.
At line:1 char:15
+ $output = try{cat C:\invalid-path.txt 2>&1}catch{$_}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\invalid-path.txt:String) [Ge
t-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
ntentCommand
Et il attrape la sortie en cas de était pas un problème avec votre commande du tout:
PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
this file is really here
Cela fonctionne pour votre exemple aussi:
PS C:\Users\jdgregson> $output = try{Test-Error *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
echo
WARNING: warning
Test-Error : error
At line:1 char:15
+ $output = try{Test-Error *>&1}catch{$_}
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,Test-Error
@JasonMArcher merci de mettre à jour les tags sur cette question! Y a-t-il quelque chose de plus que nous devrions faire puisqu'il est fixé en V3 et que j'utilisais à l'origine V2? Merci. – smaclell
Cela dépend, voulez-vous seulement des réponses à V2? Ce n'est pas un problème spécifique à V2. Ainsi, la meilleure idée est de préférer les réponses réelles à la version de PowerShell à laquelle elles sont destinées. :) – JasonMArcher
J'ai ajouté quelques notes aux réponses existantes sur la compatibilité de la version PS. – JasonMArcher