将输出流以外的两个或多个Powershell流重定向到同一文件

将输出流以外的两个或多个Powershell流重定向到同一文件,powershell,stream,io-redirection,Powershell,Stream,Io Redirection,在Powershell中,我们可以将标准输出流与任何其他流组合,然后将结果重定向(写入)到同一个文件 示例: Powershell -File "C:\myscript.ps1" 2>&1> "C:\log.txt" Powershell -File "C:\myscript.ps1" 3>&2>&1> "C:\log.txt" 假设我在myscript.ps1中使用Write Error和Write Warning语句,并且只想将错误

在Powershell中,我们可以将标准输出流与任何其他流组合,然后将结果重定向(写入)到同一个文件

示例:

Powershell -File "C:\myscript.ps1" 2>&1> "C:\log.txt"  
Powershell -File "C:\myscript.ps1" 3>&2>&1> "C:\log.txt"
假设我在myscript.ps1中使用Write Error和Write Warning语句,并且只想将错误和警告写入同一个文件

注意:如果我没有弄错的话,1是输出流,2是错误流,3是警告流

我的第一次逻辑尝试是使用3>&2>——如果将1和2结合起来有效,为什么3和2不能呢?见下文:

Powershell -File "C:\myscript.ps1" 3>&2> "C:\log.txt"
但是,3>&2>不能作为有效的重定向运算符工作

我可以四处尝试:

Powershell-文件“C:\myscript.ps1”3>“C:\warninglog.txt”2>“C:\errorlog.txt”

但我真的很想写入同一个文件

如果我尝试运行:

Powershell -File "C:\myscript.ps1" 3>"C:\log.txt" 2>"C:\log.txt" 
错误流(2)似乎永远不会写入log.txt,因为文件被警告流锁定


有没有办法将两个(或多个)输出流合并成一个流,并将结果重定向到同一个文件?

您可以将错误和警告流分别重定向到输出流,而不是执行此操作

  3>&2>&1
你应该这样做

  3>&1 2>&1
改编自

应用到您的示例中,这将成为

Powershell -File "C:\myscript.ps1" 3>&1 2>&1> "C:\log.txt"
或者,您可以将所有流重定向到您的文件

Powershell -File "C:\myscript.ps1" *> "C:\log.txt"

当您通过运行PowerShell脚本时,详细、警告和调试流将合并到标准输出中

powershell -File "C:\myscript.ps1"
所以你不能再单独重定向它们了。只有错误流是不同的,因为它似乎同时指向STDOUT和STDERR,在那里它可以被
1>
以及
2>
重定向

演示:

C:\>type test.ps1 $DebugPreference = "Continue" $VerbosePreference = "Continue" Write-Output "Output message" Write-Error "Error message" Write-Verbose "Verbose message" Write-Warning "Warning message" Write-Debug "Debug message" C:\>powershell -File .\test.ps1 Output message C:\test.ps1 : Error message + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,test.ps1 VERBOSE: Verbose message WARNING: Warning message DEBUG: Debug message C:\>powershell -File .\test.ps1 2>nul 3>nul 4>nul 5>nul Output message VERBOSE: Verbose message WARNING: Warning message DEBUG: Debug message C:\>powershell -File .\test.ps1 1>nul C:\>_ 但是,在中,您可以将任何句柄重定向到任何其他句柄(
3>&2
1>&5
,…),但只支持重定向到文件(
3>C:\out.txt
)或成功输出流(
3>&1
)。尝试重定向到任何其他流将引发错误:

C:\>powershell -Command ".\test.ps1 2>out.txt 3>&2" At line:1 char:22 + .\test.ps1 2>out.txt 3>&2 + ~~~~ The '3>&2' operator is reserved for future use. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RedirectionNotSupported 或者像这样:

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 >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"

如果要说将输出流捕获到一个变量中,并将其他流捕获到另一个变量中,则可以使用子表达式执行此操作:

$errorOutput = $( $output = & $command $arguments ) 2>&1
这是作者的一篇优秀文章