sma*_*ell 27 powershell redirect
我试图将执行脚本的整个输出(包括错误)同时写入控制台和文件.我尝试了几种不同的选择:
.\MyScript.ps1 | tee -filePath C:\results.txt # only the output to the file
.\MyScript.ps1 2> C:\results.txt # only the errors to the file and not the console
.\MyScript.ps1 > C:\results.txt # only the output to the file and not the console
Run Code Online (Sandbox Code Playgroud)
我希望我可以使用该文件来查看输出/错误.
编辑:
这是我目前的测试脚本.期望的结果是可以看到所有三个消息.
function Test-Error
{
echo "echo"
Write-Warning "warning"
Write-Error "error"
}
Test-Error 2>&1 | tee -filePath c:\results.txt
Run Code Online (Sandbox Code Playgroud)
Dav*_*ter 23
你有没有尝试过:
.\MyScript.ps1 2>&1 | tee -filePath c:\results.txt
Run Code Online (Sandbox Code Playgroud)
2>&1 是你在找什么
注意:此答案在PowerShell 1.0和2.0中运行良好,但在PowerShell 3.0及更高版本中仅捕获标准输出和错误.
我对找到的任何答案都不满意,所以我混合了几个并想出了这个(在PowerShell 3.0+中):
$output = try{your_command *>&1}catch{$_}
Run Code Online (Sandbox Code Playgroud)
通过此,您可以捕获尝试使用生成的所有错误和输出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>
Run Code Online (Sandbox Code Playgroud)
当您将无效参数传递给现有命令时,它会捕获异常:
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
Run Code Online (Sandbox Code Playgroud)
如果您的命令没有任何问题,它会捕获输出:
PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}
PS C:\Users\jdgregson> echo $output
this file is really here
Run Code Online (Sandbox Code Playgroud)
它也适用于你的例子:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77616 次 |
| 最近记录: |