当您通过以下方式运行 PowerShell 脚本时,详细、警告和调试流将合并到 STDOUT 中
powershell -File "C:\myscript.ps1"
因此您不能再单独重定向它们。只有错误流不同,因为它似乎同时进入 STDOUT 和 STDERR,可以通过 1> 和 2> 重定向。
演示:
C:\>
输入 test.ps1
$DebugPreference = "继续"
$VerbosePreference = "继续"
写输出“输出消息”
写错误“错误信息”
Write-Verbose “详细消息”
写警告“警告信息”
写调试“调试消息”
C:\>
powershell -File .\test.ps1
输出消息
C:\test.ps1:错误信息
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+fullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException,test.ps1
VERBOSE:详细信息
警告:警告信息
DEBUG:调试信息
C:\>
powershell -File .\test.ps1 2>nul 3>nul 4>nul 5>nul
输出消息
VERBOSE:详细信息
警告:警告信息
DEBUG:调试信息
C:\>
powershell -File .\test.ps1 1>nul
C:\>_
如果您想单独重定向详细、警告或调试流,您必须使用 -Command 而不是 -File 并在 PowerShell 中执行重定向:
C:\>
powershell -Command ".\test.ps1 2>$null 3>$null 5>$null"
输出消息
VERBOSE:详细信息
但是,在 CMD 中,您可以将任何句柄重定向到任何其他句柄(3>&2、1>&5、...),PowerShell redirection 仅支持重定向到文件 (3>C:\out.txt) 或成功输出流 (3>&1)。尝试重定向到任何其他流将引发错误:
C:\>
powershell -Command ".\test.ps1 2>out.txt 3>&2"
在行:1 字符:22
+ .\test.ps1 2>out.txt 3>&2
+ ~~~~
'3>&2' 运算符保留供将来使用。
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : 重定向不支持
将不同的流重定向到同一个文件:
C:\>
powershell -Command ".\test.ps1 2>out.txt 3>>out.txt"
out-file :
进程无法访问文件 'C:\out.txt' 因为它正在
被另一个进程使用。
在行:1 字符:1
+ .\test.ps1 2>out.txt 3>>out.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], IOException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
如果您可以选择合并警告和成功输出,您可以执行以下操作:
powershell -Command ".\test.ps1 >out.txt 3>&1 2>error.log"
或者像这样:
powershell -Command ".\test.ps1 >out.txt 3>&1 2>&1"
或(重定向所有流)像这样:
powershell -Command ".\test.ps1 *>out.txt"
否则我看到的唯一选择是重定向到不同的文件:
powershell -Command ".\test.ps1 3>warning.log 2>error.log"