在Azure DevOps管道中,我如何取消作业池的所有挂起作业。我有很多排队等待的作业,但找不到可以取消所有等待作业的位置。
https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=5.1
PATCH https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=5.1
参考以下 PowerShell 脚本:$url= "https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=5.1"
$pat="Personal Access Token"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$pendingJobs=Invoke-RestMethod -Uri $url-Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method get -ContentType "application/json"
$jobsToCancel = $pendingJobs.value
#Pending jobs donot consume the job agents in the agent pool. To filter the definition name to cancel pending jobs for a particular pipeline, you can use below filter criteria.
#$jobsToCancel = $pendingJobs.value | where {$_.definition.Name -eq "{Name of your pipeline }"}
#call update api to cancel each job.
ForEach($build in $jobsToCancel)
{
$build.status = "Cancelling"
$body = $build | ConvertTo-Json -Depth 10
$urlToCancel = "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($build.id)?api-version=5.1"
Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header @{Authorization = ("Basic {0}" -f $base64AuthInfo)}
}
我发现使用API的v6版本可以工作,但是不要使用PATCH而是使用DELETE。
(重用@Levi Lu-MSFT的一些代码)
$url= "https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=6.0-preview"
$pendingJobs=Invoke-RestMethod -Method GET -UseDefaultCredentials -Uri $url -ContentType "application/json"
$jobsToCancel = $pendingJobs.value
#$jobsToCancel = $pendingJobs.value | Where {$_.definition.Name -eq "{Name of your pipeline }"}
ForEach($build in $jobsToCancel)
{
$urlToCancel = "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($build.id)?api-version=6.0-preview"
Invoke-RestMethod -Uri $urlToCancel -Method DELETE -UseDefaultCredentials -ContentType application/json -Body $body
}
Invoke-RestMethod``VERBOSE: PATCH <server-url>_apis/build/builds/12495&api-version=5.0 with -1-byte payload
中出现了异常- 我已经检查了$body
,它已经完全填充并且是json格式。 - fduff&definitions=<ur-build-definitionid>
可以缩小取消操作的范围到一个构建管道。 - Dinesh Balasubramanian