如何使用PowerShell取消和删除队列中的等待构建

时间:2019-04-08 23:36:03

标签: powershell tfs build azure-pipelines azure-devops-rest-api

由于构建长期运行,各种后续内联构建需要较长时间来执行。

有没有一种方法可以取消和删除队列中的等待构建并使用PowerShell或REST API让最新触发的构建让位?

1 个答案:

答案 0 :(得分:1)

以下代码段遍历所有TFS构建,获取正在进行但尚未启动的构建,然后取消它们。

$tfsUrl = "http://{server}:{port}/{organization}/{collection}/{project}" # TFS Base URL
$BuildDefsUrl = "$tfsUrl/_apis/build/definitions?api-version=2.0" # TFS build definitions URL
$BuildsUrl = "$tfsUrl/_apis/build/builds"  #TFS Builds URL

$Builds = (Invoke-RestMethod -Uri ($BuildDefsUrl) -Method GET -UseDefaultCredentials).value | Select id,name # get all builds 
#for filtering use : |  Where-Object {$_.name -like "*Your Pattern*"}

foreach($Build in $Builds)
{
    $command = "$($BuildsUrl)?api-version=3.2-preview.3&resultFilter=inprogress&definitions=$($Build.id)&queryOrder=finishTimeDescending"

    $Ids = (((Invoke-RestMethod -Method Get -Uri $command -UseDefaultCredentials).value) | where status -like "*notStarted*").id # get waiting builds id's

    foreach($id in $Ids)
    {
            $uri =  "$($BuildsUrl)/$($id)?api-version=2.0" # TFS URI
            $body = '{"status":4}' # body 
            $result = Invoke-RestMethod -Method Patch -Uri $uri -UseDefaultCredentials -ContentType 'application/json' -Body $body -Verbose #cancel  build
    }
}