在Azure管道中,Powershell如何使任务失败?

Cla*_*ier 4 azure-powershell azure-pipelines-yaml

我正在 Windows 自托管代理上的 Azure Pipelines 上工作。我需要我的管道来运行 PowerShell 脚本,如果脚本成功,则下一阶段进行部署,否则任务失败,我们必须修复某些内容并恢复任务

我将描述管道从一开始就做什么,因为它可能有助于理解。

首先,管道调用带参数的模板:

stages:
  - template: release.yml@templates
    parameters:
      dbConnectionString: ''
Run Code Online (Sandbox Code Playgroud)

模板release.yml@templates如下:

parameters:
- name: 'dbConnectionString'
  default: ''
  type: string
Run Code Online (Sandbox Code Playgroud)

第一阶段只是简单地构建项目,工作正常

stages:
  - stage: Build
      - job: Build_Project
        steps:
          - checkout: none
          - template: build.yml          
Run Code Online (Sandbox Code Playgroud)

第二阶段取决于前一阶段的结果。对于模板的某些情况,没有要检查的数据库,因此我仅提供一个参数来运行作业。然后,我只想在 DBCheck 成功或没有参数的情况下运行 CompareFile 脚本。

  - stage: Deploy
    dependsOn: 
    - Build
    condition: eq( dependencies.Build.result, 'Succeeded' )
    jobs:
    - job: CheckDb
      condition: ne('${{ parameters.dbConnectionString }}', '')
      steps:
        - checkout: none
        - template: validate-db.yml@templates
          parameters:
            ConnectionString: '${{ parameters.dbConnectionString }}'

    - job: CompareFiles
      dependsOn: CheckDb
      condition: or( eq( dependencies.CheckDb.result, 'Succeeded' ), eq('${{ parameters.dbConnectionString }}', '') )
      steps:
        - checkout: none
        - task: PowerShell@2
          name: compareFiles
          inputs:
            targetType: filePath
            filePath: 'compareFile.ps1'

    - deployment: Deploy2
      dependsOn: CompareFiles
      environment: 'Env ST'
      strategy:
           runOnce:
             deploy:
               steps:
                - task: PowerShell@2
                  inputs:
                    targetType: filePath
                    filePath: 'File.ps1'
Run Code Online (Sandbox Code Playgroud)

接下来的工作是比较文件,CompareFile.ps1文件如下。该文件compareFileContent.ps1尝试使任务失败或成功,但我对 PowerShell 的了解不够。我发现某个地方$host.SetShouldExit(10)可能会使任务失败,所以我尝试了10失败和0成功,我也尝试了退出值,但现在,$equal = $true跳过了阶段“Deploy2”的测试,所以我被阻止了

[CmdletBinding()]
param ()

    ***

    $equal = $true

    if($equal) {
        # make pipeline to succeed
        $host.SetShouldExit(0)
    exit 0
    }
    else {
        # make pipeline to fail
        $host.SetShouldExit(10)
    exit 10
    }
Run Code Online (Sandbox Code Playgroud)

您知道为什么跳过部署作业吗?

Cla*_*ier 9

我能够使用这些退出值来使管道任务成功或失败:

if($equal) {
    # make pipeline to succeed
    exit 0
}
else {
    exit 1
}
Run Code Online (Sandbox Code Playgroud)

我在自己的阶段而不是在作业中使用了 PowerShell 脚本,并且它有效,当任务失败时,我可以执行所需的手动操作并再次运行该任务。

干杯,克劳德