PowerShell中如何分别重定向警告/错误流与详细/调试流至不同文件?
PowerShell 5.1 多流重定向问题解决方案
你遇到的问题是PowerShell 5.1的原生重定向机制限制导致的:
3>&2这类非标准流(流3-6)之间的重定向语法,在PowerShell 5.1中尚未实现,属于预留语法,因此会触发解析错误。- 直接将多个流指定到同一文件时,每个重定向操作会独立打开文件并加锁,导致后续写入操作因文件被占用失败。
针对PowerShell 5.1的可行方案
通过脚本块收集所有输出流,再根据输出对象的类型筛选写入对应文件:
& { # 将错误、警告、详细、调试流全部重定向到成功流(流1) .\test-streams.ps1 -Debug -Verbose 2>&1 3>&1 4>&1 5>&1 } | ForEach-Object { # 根据输出对象类型判断写入目标文件 switch ($_.GetType().Name) { 'ErrorRecord' { $_ | Out-File -Append -Path test-streams.err } 'WarningRecord' { $_ | Out-File -Append -Path test-streams.err } 'VerboseRecord' { $_ | Out-File -Append -Path test-streams.verbose } 'DebugRecord' { $_ | Out-File -Append -Path test-streams.verbose } default { $_ | Out-File -Append -Path test-streams.log } } }
执行前需确保目标文件不存在,或通过-Append参数避免覆盖已有内容。
更简洁的解决方案:升级到PowerShell 7+
PowerShell 7及以上版本已支持非标准流之间的重定向,同时优化了文件锁定逻辑,可直接用原生语法实现需求:
.\test-streams.ps1 -Debug -Verbose ` 1> test-streams.log ` 2> test-streams.err ` 3>&2 ` 4> test-streams.verbose ` 5>&4
此命令实现:
- 成功流(1)写入
test-streams.log - 错误流(2)和警告流(3)写入
test-streams.err - 详细流(4)和调试流(5)写入
test-streams.verbose
内容的提问来源于stack exchange,提问作者Peyre
相关产品推荐
相关产品推荐

