我对找到的任何答案都不满意,所以我混合了一些并想出了这个(在 PowerShell 3.0+ 中):
$output = try{your_command *>&1}catch{$_}
通过它,您可以捕获尝试使用your_command 生成的所有错误和输出。
当你使用不存在的命令时它会捕获异常:
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>
当您将无效参数传递给现有命令时,它会捕获异常:
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
如果您的命令完全没有问题,它会捕获输出:
PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
this file is really here
它也适用于您的示例:
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