You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中进程ExitCode字符串拼接报错的解决方法

解决PowerShell中进程ExitCode字符串拼接的类型转换错误

问题根源在于PowerShell的字符串插值解析逻辑:在双引号字符串中直接写$process.ExitCode时,PowerShell会将$process识别为变量,而后续的.ExitCode会被当作普通文本处理。这会导致脚本尝试将整个Process对象转换为字符串,进而触发类型转换错误。

要正确实现期望的输出,需要用**子表达式$()**包裹属性访问表达式,让PowerShell先计算出$process.ExitCode的具体数值,再将结果插入到字符串中。

修正后的关键代码行

将第7行替换为:

Write-Output "Error: $($process.ExitCode)"

完整修正脚本

$a = "C:\Temp\"
$b = "out.txt"
$c = "out.bat"
$process = Start-Process -FilePath "${a}${c}" -ArgumentList "123" -RedirectStandardOutput ${a}${b} -Wait -PassThru
Get-Content ${a}${b}
Write-Output $process.ExitCode
Write-Output "Error: $($process.ExitCode)"

执行后,第7行将正常输出类似Error: 0的结果(具体数值取决于进程实际退出码)。

替代方案:使用字符串拼接运算符

如果偏好显式拼接,也可以用+运算符实现:

Write-Output ("Error: " + $process.ExitCode)

内容的提问来源于stack exchange,提问作者ShieldOfSalvation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:20:31