如何在Powershell中将指定报错信息输出到文本文件
实现代码
修改后的脚本如下,可直接输出bat返回的纯文本内容,无PowerShell附加错误字段:
Invoke-Command -ComputerName 1.1.1.1 -Credential KOPI\Administrator -ScriptBlock { # 合并标准输出、标准错误流,统一提取原始文本 & cmd.exe /c 'C:\Users\Administrator.KOPI\Documents\test.bat' 2>&1 | ForEach-Object { $_ -is [System.Management.Automation.ErrorRecord] ? $_.Exception.Message : $_ } } | Out-File (Join-Path $PSScriptRoot hello.txt) -Encoding UTF8
注:上述代码中的三元表达式兼容PowerShell 7及以上版本,若需适配PowerShell 5.1及更早版本,可将ForEach-Object内部逻辑替换为:
if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { $_ }
逻辑说明
- 原问题根因:PowerShell默认会将外部程序输出到错误流的内容封装为
ErrorRecord对象,远程调用场景下会进一步包装为RemoteException,自动追加CategoryInfo、FullyQualifiedErrorId等元字段 2>&1参数将cmd的标准错误流合并到标准输出流,避免内容被识别为PowerShell错误抛出- 对每一条输出做类型判断:如果是错误记录对象,仅提取原生异常消息;正常输出直接透传
- 最终写入文件的内容仅包含bat脚本自身输出的原始信息
内容的提问来源于stack exchange,提问作者Gaming
相关产品推荐
相关产品推荐

