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

如何解决Jenkins运行PowerShell脚本出现'script returned exit code 1'报错

方案1:PowerShell脚本内控制返回码(优先推荐)

PowerShell无需修改全局执行模式,可在调用Unity测试命令的行单独捕获返回值,避免非0返回码触发脚本整体失败,等效于bash的set +e效果:

# 执行Unity单元测试,忽略非0退出码,单独保存返回值
$unityTestExitCode = 0
& Unity.exe -runTests -batchmode -projectPath . -testResults TestResults.xml -testPlatform EditMode || $unityTestExitCode = $LASTEXITCODE

# 可按需处理返回码,比如输出失败日志但不终止流程
if ($unityTestExitCode -ne 0) {
    Write-Host "单元测试存在用例失败,退出码:$unityTestExitCode"
}

# 脚本结束显式返回0,让Jenkins判定步骤执行成功
exit 0

上述写法中||为短路运算符,仅当前面的Unity命令返回非0时才会赋值返回码变量,整行语句不会抛出错误,也不会导致脚本整体返回非0。

方案2:Jenkins端配置忽略脚本返回码

如果不想修改原有PowerShell脚本,可直接在Jenkins任务中调整执行逻辑:

2.1 Freestyle任务配置

  • 在「构建」步骤选择「执行Windows PowerShell」时,用cmd命令包裹执行,强制忽略返回值:
    cmd /c "powershell -File your_test_script.ps1"
  • 或直接在PowerShell步骤的最后一行追加exit 0,覆盖原有脚本的返回值。

2.2 Pipeline(Jenkinsfile)配置

通过returnStatus参数捕获返回码,不会因为非0返回终止构建流程:

pipeline {
    agent any
    stages {
        stage('Run Unity Tests') {
            steps {
                script {
                    // returnStatus=true会将命令返回值作为变量返回,不抛出异常终止构建
                    def testExitCode = powershell returnStatus: true, script: '.\\your_test_script.ps1'
                    echo "Unity测试返回码:${testExitCode}"
                    // 可自行扩展处理逻辑,比如统计失败用例数量但继续执行后续步骤
                }
            }
        }
        stage('后续构建步骤') {
            steps {
                echo '构建流程正常继续执行'
            }
        }
    }
}

注:两种方案都不会影响JUnit等插件解析测试报告,只要Unity正常输出了测试结果文件,即可正常展示测试统计数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:06:03