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

Azure Pipeline中AzurePowerShell任务实现Wiki存在性判断逻辑

解决Azure DevOps流水线重复创建Wiki报错问题

问题场景

现有Azure DevOps构建流水线中的AzurePowerShell@5任务,用于从指定代码仓库创建Wiki。首次运行流水线可成功创建Wiki,但后续运行时会抛出如下错误:

{"$id":"1","innerException":null,"message":"Wiki already exists with name 'wiki'.","typeName":"Microsoft.TeamFoundation.Wiki.Server.WikiAlreadyExistsException, Microsoft.TeamFoundation.Wiki.Server","typeKey":"WikiAlreadyExistsException","errorCode":0,"eventId":3000}

需求是实现条件判断:仅当目标Wiki不存在时执行创建操作,否则跳过脚本。

解决方案

修改PowerShell内联脚本,添加前置查询检查逻辑:先调用Azure DevOps Wiki API查询目标名称的Wiki是否存在,根据查询结果决定是否执行创建操作。

修改后的完整任务代码

- task: AzurePowerShell@5
  inputs:
      azureSubscription: '$(service_connection)'
      ScriptType: 'InlineScript'
      Inline: |
        $wikiName = "wiki"
        # 构造查询指定名称Wiki的API地址
        $checkUrl = "https://dev.azure.com/data-platform/uc_test/_apis/wiki/wikis?api-version=6.0&name=$wikiName"
        
        try {
            # 发送GET请求查询Wiki是否存在
            $existingWiki = Invoke-RestMethod -Uri $checkUrl -Headers @{Authorization = "Bearer $(System.AccessToken)"} -Method Get -ContentType application/json
            if ($existingWiki.count -gt 0) {
                Write-Host "Wiki '$wikiName' 已存在,跳过创建操作"
                return
            }
        } catch {
            # 若返回404,说明Wiki不存在,继续执行创建逻辑
            if ($_.Exception.Response.StatusCode.value__ -eq 404) {
                Write-Host "Wiki '$wikiName' 不存在,开始创建"
            } else {
                # 其他异常直接抛出
                throw $_
            }
        }

        # 构造创建Wiki的请求体
        $createUrl = "https://dev.azure.com/data-platform/uc_test/_apis/wiki/wikis?api-version=6.0"
        $body= @'
        {
          "version": {
            "version": "main"
          },
          "type": "codeWiki",
          "name": "wiki",
          "projectId": "c800c392-67aa-4892-a070-7284435bda9b",
          "repositoryId": "2avd6061-b265-417f-8b55-81cc65kf90b6",
          "mappedPath": "/"
        }
        '@
        
        # 执行创建操作
        $response = Invoke-RestMethod -Uri $createUrl -Headers @{Authorization = "Bearer $(System.AccessToken)"} -Method Post -Body $body -ContentType application/json 
        Write-Host "Wiki 创建成功,响应内容:$($response | ConvertTo-Json -Depth 10)"
      azurePowerShellVersion: 'LatestVersion'

逻辑说明

  1. 查询检查:通过带name参数的GET请求查询目标Wiki,若返回结果数量大于0,说明Wiki已存在,直接跳过创建。
  2. 异常处理:若查询返回404状态码,说明Wiki不存在,进入创建流程;其他异常(如权限不足)则直接抛出,便于排查问题。
  3. 创建操作:仅当Wiki不存在时,才执行POST请求创建Wiki。

注意事项

  • 确保流水线的System.AccessToken拥有对目标项目的Wiki读取和创建权限。
  • 可根据实际需求调整api-version、项目ID、仓库ID等参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:35:21