在Jenkins中使用PsExec,即使脚本失败,也显示Success

Using PsExec in Jenkins, even if the script fails, it shows Success

我正在尝试 运行 一个 powershell 脚本,该脚本首先登录到 azure,然后使用 psexec 将 zip 文件部署到 azure。

我正在使用以下命令:

F:\jenkins\VMScripts\PsExec64.exe \WINSU9 -u "WINSU9\administrator" -p mypassword /accepteula -h PowerShell -noninteractive -File C:\Shared\Trial\webappscript.ps1

我得到的输出为:

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

[
  {
    "cloudName": "AzureCloud",
    "id": "a7b6d14fddef2",
    "isDefault": true,
    "name": "subscription_name",
    "state": "Enabled",
    "tenantId": "b41cd",
    "user": {
      "name": "username@user.com",
      "type": "user"
    }
  }
]
WARNING: Getting scm site credentials for zip deploymentConnecting to WINSU9...


Starting PSEXESVC service on WINSU9...


Connecting with PsExec service on WINSU9...


Starting PowerShell on WINSU9...



PowerShell exited on WINSU9 with error code 0.
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

它只是给出了 az login 命令的输出,但没有显示部署的输出。此外,如果部署失败,它仍会显示成功。但是应该显示失败。

Jenkins 作业成功,因为 PSExec.exe 返回了退出代码 0,这意味着没有遇到任何错误。如果底层脚本失败(例如返回非零退出代码,如 1),Jenkins 作业将失败。如果 PSExec.exe 应用程序没有按照您的意愿执行 - 我会将其包装在另一个执行 post-deploy 验证的脚本中,如果部署 returns 1失败。

有关详细信息,请参阅 How/When does Execute Shell mark a build as failure in Jenkins?

回答我的问题,以便遇到同样问题的其他人可以在这里获得帮助。
正如@Alex 所说,powershell 正在退出,错误代码为 0,每当任何命令失败时,我都尝试 return 错误代码 1。由于 Azure CLI 的输出采用 json 格式,我将该输出存储在一个变量中并检查它是否包含任何内容。代码示例如下。

$output = az login -u "username" -p "password" | ConvertFrom-Json
if (!$output) {
    Write-Error "Error validating the credentials"
    exit 1
}

你可以使用powershell step,这样应该也能直接报错