我正在尝试在PowerShell中编写一个简单的测试脚本,以将警告消息与stdout/result分开,以便获得两个单独的文本文件,一个用于警告,另一个用于PowerShell重定向中的标准结果。
这是我的简单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.
它将按预期生成错误,以error.txt
results.txt
其中results.txt
是警告和标准输出/结果的组合。warning.txt
仍然是空的。我仍然无法弄清楚为什么PowerShell警告没有被过滤并正确重定向到单独的文件。
错误.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:UsersDellDesktopoutput.ps1:3 char:1
+ This will generate error because this is not a ps command.
+ ~~~~
+ CategoryInfo : ObjectNotFound: (this:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
结果.txt:
This is result
WARNING: This is warning
我使用的是Windows 10和PowerShell版本5.1.14393.1358。
在下面的示例中,真正的问题是,当您使用powershell.exe
详细执行 ps1 文件时,警告和调试流将合并到STDOUT 中)-源。(---导致空白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.
然后创建另一个电源外壳文件。(我称之为newout.ps1
),newout.ps1
可以使用以下内容运行output.ps1
。
.output.ps1 2>error.txt 3>warning.txt >results.txt
最后,您的 bat 文件可以以这种方式运行newout.ps1
1 而不是output.ps1
。
PowerShell.exe -Command "& '%~dp0newout.ps1'"
这为您提供了三个具有所需结果的单独文件。