【问题标题】:How to separate warning message from stdout/result in powershell redirection?如何在powershell重定向中将警告消息与标准输出/结果分开?
【发布时间】:2017-10-28 03:52:48
【问题描述】:

我正在尝试在 PowerShell 中为separate warning message from stdout/result 编写一个简单的测试脚本,以便在PowerShell Redirection 中获得两个单独的文本文件,一个用于警告,一个用于标准结果。

这是我的简单output.ps1 脚本:

Write-Output "This is result"
Write-Warning "This is warning"

我正在尝试使用以下命令使用 .bat 文件运行 output.ps1

PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt
pause

但我的问题是warning.txt 完全为空,而警告和结果都写入results.txt

This is result
WARNING: This is warning

我在PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt 中缺少将警告和错误分成两个文件的内容?


编辑:修改为查看标准错误,2> 正在工作。

即使我通过使用 2>error.txt 将标准错误重定向到单独的文件

PowerShell.exe -Command "& '%~dp0output.ps1'" 2>error.txt 3>warning.txt >results.txt

如果我修改output.ps1 以按以下方式生成错误

Write-Output "This is result"
Write-Warning "This is warning""
This will generate error because this is not a ps command.

它将按预期将错误生成到带有results.txt 的文件error.txt,其中results.txt 是警告和标准输出/结果的组合。 warning.txt 仍然是空的。我仍然无法弄清楚为什么 PowerShell 警告没有被过滤并正确重定向到单独的文件。

error.txt:

this : The term 'this' 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 C:\Users\Dell\Desktop\output.ps1:3 char:1
+ This will generate error because this is not a ps command.
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (this:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

results.txt:

This is result
WARNING: This is warning

我使用的是 Windows 10 和 PowerShell 版本 5.1.14393.1358。

【问题讨论】:

  • 2>warning.txt 呢?
  • powershell/cmd 无法重定向警告可能是?它可以使用 2> .. 重定向的错误,但 3> 将生成空白输出
  • 据我所知,cmd只有错误和标准流。

标签: powershell cmd warnings stdout batch-processing


【解决方案1】:

在下面的示例中,真正的问题是,当您使用powershell.exe 执行 ps1 文件时 verbosewarningdebug > 流合并到 STDOUT) -Source。 (---导致空白warning.txt)

    PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt  

为了规避powershell.exe 中的这个限制,上面的例子有一个解决方法,使用额外的中间 ps1 文件。您可以使用两个 powershell 文件和一个 bat 文件,并为 error/warning/results 获取三个单独的文件。 (2>error.txt 3>warning.txt >results.txt)

output.ps1 的内容与以下内容相同。

Write-Output "This is result"
Write-Warning "This is warning""
This will generate error because this is not a ps command.

然后创建另一个 powershell 文件。 (我称它为newout.ps1)和newout.ps1 可以运行output.ps1,内容如下。

.\output.ps1 2>error.txt 3>warning.txt >results.txt

你的 bat 文件终于可以以这种方式运行 newout.ps11 而不是 output.ps1

PowerShell.exe -Command "& '%~dp0newout.ps1'"

这会为您提供三个具有所需结果的单独文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多