如何使自定义 Visual Studio Team Services 构建任务失败(使用 PowerShell)?

How do you make a custom Visual Studio Team Services build task fail (using PowerShell)?

我创建了一个 Visual Studio Team Services 扩展,它提供了几个构建任务。所有任务都作为 PowerShell 脚本实现。

一切似乎都按预期工作,但后来我意识到,当一个任务出现错误时,并没有像它应该的那样破坏构建。

我原以为返回非零退出代码的 PowerShell 脚本会破坏构建,但事实并非如此。为了确认这一点,我只用这一行创建了一个非常简单的任务:

exit 1

并检查构建是否成功。

我还发现脚本中未捕获的异常确实会导致构建失败。

因此,应该如何从构建任务中通知失败?

更新:我正在使用 task.json 和脚本:

task.json:

{
 "id": "7CA6E75B-0700-4723-83A7-C167EA514988",
 "name": "ExampleTask",
 "friendlyName": "Example build task",
 "description": "Example build task for development purposes",
 "author": "eduardomhg",
 "category": "Utility",
 "visibility": [
   "Build",
   "Release"
 ],
 "demands": [],
 "version": {
   "Major": "0",
   "Minor": "0",
   "Patch": "1"
 },
 "minimumAgentVersion": "1.83.0",
 "instanceNameFormat": "Example Task",
 "groups": [
       {
           "name":"advanced",
           "displayName":"Advanced",
           "isExpanded":false
       }
   ],
 "execution": {
   "PowerShell": {
     "target": "$(currentDirectory)\ExampleTask.ps1",
     "argumentFormat": "",
     "workingDirectory": "$(currentDirectory)"
   }
 }
}

示例任务。ps1:

 Write-Host "Executing example task..."
 exit 1

TL;DR

基于 PowerShell 开发自定义任务时:

  • PowerShell 脚本在完成工作后应该 return 0,不尊重结果是肯定的还是否定的。
  • 当任务无法正确完成时(例如基础结构问题、语法错误或意外异常等),它必须 return 不是 0 的值。
  • 当任务的作业完成时,失败或成功必须始终与 VSTS Task Lib SDK 的 Write-VstsSetResult API(或 ##vso[task.complete] 命令)进行通信。


详细信息:您在 'task.json' 文件的“执行”部分中指定的 vsts-agent starts the PowerShell scripts using C# classes so called 'Handlers';可能的基于 PS 的处理程序是:

  • PowerShell3
  • PowerShell
  • PowerShellExe

PowerShell3”(或已弃用的“PowerShell”)处理程序:

  • 基于PowerShell创建自定义任务时必须使用;这意味着您的任务至少捆绑了一个 PS 脚本,该脚本在“execute”部分的 task.json 中指定;

  • 期望退出代码等于 0,无论任务的结果是什么(成功或失败);

  • 当脚本执行期间出现内部错误时,期望一个不同于 0 的值,这意味着脚本无法完全完成其工作,即当任务的工作结果甚至不知道。简而言之,退出代码与任务作业的 positive/negative 结果无关。当作业完成时(无论是消极的还是积极的),退出代码必须为 0。 规定退出代码等于 0 的要求:

这在构建摘要中也很清楚,当 returning 退出代码不同于 0 时(例如,使用 [Environment]::Exit(1) 时,构建摘要会变得混乱,如红色框所示) . 相反,当使用 0 退出代码正常退出失败任务并使用 Write-VstsSetResult API(绿色框)设置结果时,您会得到一个干净的构建摘要。

相反,'PowerShellExe' 处理程序执行最终用户提供的 PowerShell 脚本:在这种情况下,此处理程序遵循普通命令制服的普通规则,即: - 结果状态等于 0 表示执行成功; - 不同于 0 的结果表示执行失败;


更多详情

在利用 VSTS Task SDK functions it is possible to issue some commands to the agent. One of them is to tell the result (either success of failure) of the execution of the task: this can be done by calling the API function Write-VstsSetResult

基于 PowerShell 开发自定义任务时

否则,如果无法使用 SDK,无论如何都可以在标准输出上打印以下命令:

##vso[task.complete result=Succeeded|SucceededWithIssues|Failed|Cancelled|Skipped]

这与 Write-VstsSetResult 函数在下面使用的命令相同。

代理确实拦截并使用了任务的标准输出,它识别命令并执行它。

当任务能够完成它的工作时(无论是失败还是成功),它必须 return 退出代码 0 并使用上述命令设置结果。只有当任务无法完成其工作时,才必须使用不同于 0 的退出代码进行通信。

您可以添加以下行来使任务失败:

"##vso[task.complete result=Failed]"

这将告诉 VSTS 任务失败。

尝试改用此代码:

[Environment]::Exit(1)