Created
September 6, 2022 09:20
-
-
Save rfennell/2f51bc6a4c02e5c8021eb1b01f948ca4 to your computer and use it in GitHub Desktop.
A sample script that shows how to find the Azure DevOps agent pool for a named agent. Also shows the call required to delete the agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-AgentPoolForNamedAgent { | |
param | |
( | |
$pat, | |
$url, | |
$agentName | |
) | |
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)")) | |
$repoHeader = @{"Authorization"="Basic $patToken"} | |
# get the pool ID from the name | |
$uri = "$url/_apis/distributedtask/pools?api-version=7.1-preview.1" | |
# usin the invoke-restmethod as it allow the same form to be used for get and delete calls | |
$jsondata = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10 | |
foreach ($pool in $jsondata.value) | |
{ | |
Write-Host "Processing Agent Pool '$( $pool.name )'" | |
# Get agents of an agent pool (Request method: Get): | |
$pooluri = "$url/_apis/distributedtask/pools/$($pool.id)/agents?api-version=7.1-preview.1" | |
$agentJsondata = Invoke-RestMethod -Uri $pooluri -Method Get -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10 | |
foreach ($agentRec in $agentJsondata.value) { | |
Write-Host "Processing Agent '$( $agentRec.name )'" | |
if ($agentRec.name -match $agentName) { | |
Write-Host "Agent '$($agentName)' [$($agentRec.id)] found in pool '$( $pool.name )' [$($pool.id)]" | |
# we are exiting the function here with the pool information but you have enough informaton to delete the agent using a call to | |
# DELETE https://dev.azure.com/{organization}/_apis/distributedtask/pools/{poolId}/agents/{agentId}?api-version=7.1-preview.1 | |
# smethink like | |
# $deleteUri = "$url/_apis/distributedtask/pools/$($pool.id)/agents/$($agentRec.id)?api-version=7.1-preview.1" | |
# Invoke-RestMethod -Uri $deleteUri -Method Delete -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10 | |
return $pool | |
} | |
} | |
} | |
} | |
# Usage | |
# Get-AgentPoolForNamedAgent -url https://dev.azure.com/yourorg -agentName my-agent -pat <yourpat> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment