PowerShell重定向stderr至stdout时输出乱序的原因及解决方法
关于PowerShell重定向stderr时输出顺序异常的原因与解决方法
测试工具说明
原生命令output(.exe)会按照命令行参数指定的顺序,分别向标准输出(stdout)和标准错误(stderr)写入内容。
各环境测试结果
macOS 下的 PowerShell 7.2
PS> ./output -o 1 -e 2 -o 3 1 2 3 PS> ./output -o 1 -e 2 -o 3 2>&1 1 3 2
macOS 下的 Zsh
% ./output -o 1 -e 2 -o 3 1 2 3 % ./output -o 1 -e 2 -o 3 2>&1 1 2 3
Windows PowerShell 5.1
(重定向时stderr会被包装成错误信息,但输出顺序和macOS上的PowerShell 7.2一致)
PS> .\output.exe -o 1 -e 2 -o 3 1 2 3 PS> .\output.exe -o 1 -e 2 -o 3 2>&1 1 3 ./output.exe : 2 At line:1 char:1 + ./output.exe -o 1 -e 2 -o 3 2>&1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (2:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError
Windows 命令处理器(cmd.exe)
C:\> .\output.exe -o 1 -e 2 -o 3 1 2 3 C:\> .\output.exe -o 1 -e 2 -o 3 2>&1 1 2 3
原因分析
PowerShell处理原生程序输出时,会将stdout和stderr视为两个独立数据流分别读取:
- 不做重定向时,PowerShell会实时将两个流的内容输出到控制台,因此能保持原生程序的输出顺序。
- 使用
2>&1重定向时,PowerShell会先完整读取原生程序的stdout内容,再读取stderr内容,之后才将两者合并输出。这就导致原本穿插在stdout中的stderr内容被后置,破坏了原有顺序。
另外,Windows PowerShell 5.1会把stderr内容包装成PowerShell错误对象,这就是出现额外错误信息的原因;PowerShell 7+虽不再包装,但顺序问题依然存在。
修改行为的方法
方法1:使用Start-Process命令
通过Start-Process可以强制保持输出顺序,同时合并流:
# 分别捕获后合并输出 Start-Process -NoNewWindow -Wait -FilePath ./output.exe -ArgumentList "-o 1 -e 2 -o 3" -RedirectStandardOutput temp.out -RedirectStandardError temp.err Get-Content temp.out, temp.err Remove-Item temp.out, temp.err # 直接合并到同一文件后读取 Start-Process -NoNewWindow -Wait -FilePath ./output.exe -ArgumentList "-o 1 -e 2 -o 3" -RedirectStandardOutput combined.out -RedirectStandardError combined.out Get-Content combined.out Remove-Item combined.out
方法2:借助cmd.exe的重定向逻辑(适用于PowerShell全版本)
利用cmd.exe的原生重定向规则来保持输出顺序:
cmd /c '.\output.exe -o 1 -e 2 -o 3 2>&1'
或者用--%停止解析符号,避免PowerShell处理重定向参数:
& cmd /c --% .\output.exe -o 1 -e 2 -o 3 2>&1
方法3:抑制Windows PowerShell 5.1的错误包装(仅解决格式问题,不修复顺序)
通过修改偏好设置,去掉stderr对应的错误对象附加信息:
$ErrorActionPreference = 'SilentlyContinue' .\output.exe -o 1 -e 2 -o 3 2>&1 $ErrorActionPreference = 'Continue' # 恢复默认设置
内容的提问来源于stack exchange,提问作者Michiel van Oosterhout
相关产品推荐
相关产品推荐

