我想将所有输出重定向到文件(*> 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
我也尝试合并没有运气的流:
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
进行了一些尝试,但也无法使它正常工作。问题似乎在于您不能多次重定向流或将其输出到两个位置?有没有办法解决这个问题或以某种巧妙的方式解决它?
答案 0 :(得分:0)
没有一种简单的方法来获取此信息,因为您无法重定向到两个不同的地方。
如果您的逻辑不太复杂,则应执行以下操作:
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.GetChildItemCommand
all.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.GetChildItemCommand