Powershell将所有输出流重定向到文件,将错误重定向到控制台

问题描述 投票:0回答:1

我想将所有输出重定向到文件(*> 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也做了一些尝试,但也无法使它正常工作。问题似乎在于您不能多次重定向流或将其输出到两个位置?有没有办法解决这个问题或以某种巧妙的方式解决它?

powershell io-redirection
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.