我希望将所有输出重定向到一个文件(*> file),并且只将错误重定向到控制台(2>),但找不到这样做的方法。
尝试执行此操作后会出现错误:
Write-Error "error" *> all.log 2>
+ Write-Error "error" *> all.log 2>
+ ~
Missing file specification after redirection operator.我试着按照错误消息的提示添加一个file,看看重定向在这种情况下是否可以工作,但它不能:
Write-Error "error" *> all.log 2> errors.log
# all.log is empty but should contain the error also
# errors.log contains error我还尝试了组合streams,但没有成功:
Write-Error "error" 2>&1 all.log 2> errors.log
+ Write-Error "error" 2>&1 all.log 2> errors.log
+ ~~~~~~~~~~~~~
The error stream for this command is already redirected.我也尝试过用tee做一些事情,但也不能正常工作。看起来问题是你不能多次重定向一个流或者把它输出到两个地方?有没有办法绕过这个问题,或者以一种整洁的方式解决它?
发布于 2020-04-22 21:03:47
没有一种简单的方法可以获得它,因为你不能重定向到两个不同的地方。
如果你的逻辑不是太复杂,这样的东西应该可以工作:
function Redirect($output)
{
# If the last operation was a success $? will be true
if($?)
{
$output | Out-File -FilePath "all.log" -Append
}
else
{
# $Error[0] is the message of the last error which was already displayed on the screen
$Error[0] | Out-File -FilePath "all.log" -Append
}
}
Redirect (Get-ChildItem "exists")
Redirect (Get-ChildItem "nonexistent")在命令行中,输出如下所示:
PS C:\temp> C:\temp\test.ps1
Get-ChildItem: Cannot find path 'C:\temp\nonexistent' because it does not exist.
At C:\temp\test.ps1:15 char:11
+ Redirect (Get-ChildItem "nonexistent")
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\temp\nonexistent:String) [Get-ChildItem], ItemNotF
oundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommandAll.log的内容:
Directory: C:\temp\exists
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2020-04-22 8:44 AM 0 here.txt
Get-ChildItem : Cannot find path 'C:\temp\nonexistent' because it does not exist.
At C:\temp\test.ps1:15 char:11
+ Redirect (Get-ChildItem "nonexistent")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\temp\nonexistent:String) [Get-ChildItem], ItemNotF
oundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommandhttps://stackoverflow.com/questions/61348495
复制相似问题