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

WSL环境下Ubuntu 20调用PowerShell脚本无法正确获取退出码

问题原因
  1. PowerShell catch块逻辑错误
    你编写的catch块中先执行了return 1,该语句会直接退出当前作用域,后续的exit 1永远不会被执行。且return只会将数值作为返回值输出到标准输出(这也是你日志中出现单独一行1的原因),不会设置PowerShell进程的退出码。另外你贴出的catch块代码缺少闭合的},也可能导致语法逻辑异常。
  2. PowerShell调用参数不合理
    如果你使用-Command参数执行PowerShell脚本,默认情况下PowerShell进程的退出码仅代表本身是否成功启动并完成命令执行,不会自动传递脚本内部的退出码,只有-File参数会默认将脚本的exit code作为进程退出码返回。
解决方法
  1. 修正PowerShell catch块代码
    删除多余的return语句,直接用exit设置进程退出码,同时补全缺失的闭合大括号:
catch {
    $message = "## Package executed with error: " + $PSItem.ToString()
    Write-Host $message
    exit 1
}
  1. 修正Bash中的PowerShell调用语句
    优先使用-File参数执行ps1脚本,该参数会自动传递脚本退出码:
"${PowerShellLocation}" -File "${pws}"
ReturnCode=$?
echo "## ReturnCode Powershell:" ${ReturnCode}

如果你的场景必须使用-Command参数(例如传入的是PowerShell命令片段而非脚本文件路径),需要显式在命令末尾返回脚本的退出码:

"${PowerShellLocation}" -Command "& ${pws}; exit \$LASTEXITCODE"
ReturnCode=$?
echo "## ReturnCode Powershell:" ${ReturnCode}

注意上述命令中的\是为了转义$,避免$LASTEXITCODE被Bash提前解析。
3. 验证修复结果
直接在WSL终端手动执行修正后的PowerShell调用命令,执行完成后输入echo $?,确认返回值为预期的1即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:15:00