Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Delete Deployments from a ResourceGroup Using Jobs and a Service Principal
#this script will delete deployments from a resourceGroup if the number of deployments exceeds the number specified by the Max parameter
[string] [Parameter(Mandatory = $true)] $ResourceGroupName,
[int] [Parameter(Mandatory = $true)] $Max,
[string] [Parameter(Mandatory = $true)] $tenantId,
[string] [Parameter(Mandatory = $true)] $ServicePrincipalId,
[securestring] [Parameter(Mandatory = $true)] $ServicePrincipalSecret,
[string] [Parameter(Mandatory = $true)] $SubscriptionId
$creds = New-Object System.Management.Automation.PSCredential ($ServicePrincipalId, $ServicePrincipalSecret)
Connect-AzAccount -ServicePrincipal -Credential $creds -TenantId $tenantId
Set-AzContext -Subscription $SubscriptionId
$deployments = Get-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName
if ($deployments.Count -gt $Max) {
$numToDelete = $deployments.Count - $Max
$i = 1
while ($i -le $numToDelete) {
write-host "Deleting Deployment: "$deployments[$deployments.Count - $i].DeploymentName
Start-Job -Name $deployments[$deployments.Count - $i].DeploymentName {
Param($RGName, $deploymentName, $creds, $tenantId, $SubscriptionId)
Connect-AzAccount -ServicePrincipal -Credential $creds -TenantId $tenantId
Set-AzContext -Subscription $SubscriptionId
Remove-AzResourceGroupDeployment -ResourceGroupName $RGName -Name $deploymentName -Verbose
} -ArgumentList $ResourceGroupName, $deployments[$deployments.Count - $i].DeploymentName, $creds, $tenantId, $SubscriptionId
Get-Job | Wait-Job | Receive-Job
Copy link

bmoore-msft commented Sep 16, 2019

Azure PowerShell doesn't always handle context in jobs correctly, so the script forces a login for each job. This works fine but requires passing Service Principal Credentials to the script.

See: this gist for a simpler serial version of the script.

Alternatively, you could get the token from the cache for the current context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment