首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell将所有输出流重定向到文件,并将错误重定向到控制台

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

Stack Overflow用户
提问于 2020-04-22 00:36:09
回答 1查看 429关注 0票数 0

我希望将所有输出重定向到一个文件(*> file),并且只将错误重定向到控制台(2>),但找不到这样做的方法。

尝试执行此操作后会出现错误:

代码语言:javascript
复制
Write-Error "error" *> all.log 2>

+ Write-Error "error" *> all.log 2>
+                                 ~
Missing file specification after redirection operator.

我试着按照错误消息的提示添加一个file,看看重定向在这种情况下是否可以工作,但它不能:

代码语言:javascript
复制
Write-Error "error" *> all.log 2> errors.log
# all.log is empty but should contain the error also
# errors.log contains error

我还尝试了组合streams,但没有成功:

代码语言:javascript
复制
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做一些事情,但也不能正常工作。看起来问题是你不能多次重定向一个流或者把它输出到两个地方?有没有办法绕过这个问题,或者以一种整洁的方式解决它?

EN

回答 1

Stack Overflow用户

发布于 2020-04-22 21:03:47

没有一种简单的方法可以获得它,因为你不能重定向到两个不同的地方。

如果你的逻辑不是太复杂,这样的东西应该可以工作:

代码语言:javascript
复制
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")

在命令行中,输出如下所示:

代码语言:javascript
复制
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的内容:

代码语言:javascript
复制
    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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61348495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档