Created
January 3, 2020 18:28
this is the PowerShell script that deletes every resource in a given resource group. It was demonstrated in my video about Azure Automation in the Azure Advent Calendar series (https://www.youtube.com/watch?v=N1ktTy08xDs)
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
workflow Empty-Resource-Group | |
{ | |
param( | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[string] | |
$ResourceGroupName, | |
[Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] | |
[String] | |
$SubscriptionId | |
) | |
# Login to Azure | |
$connection = Get-AutomationConnection -Name AzureRunAsConnection | |
Login-AzAccount -ServicePrincipal -Tenant $connection.TenantID ` | |
-ApplicationId $connection.ApplicationID ` | |
-CertificateThumbprint $connection.CertificateThumbprint | |
Select-AzSubscription -SubscriptionId $SubscriptionId | |
Write-Output "Connected to Azure!" | |
#Get the Azure Resource Group | |
$rg = Get-AzResourceGroup -Name $ResourceGroupName; | |
if(!$rg){ | |
Write-Output "Resource Group $ResourceGroupName does not exist."; | |
} | |
else{ | |
Write-Output "Deleting resources..." | |
# Get all resources in the resource group | |
$resources = (Get-AzResource | where { $_.ResourceGroupName -match $ResourceGroupName }); | |
Foreach -parallel ($resource in $resources) { | |
if($resource.ResourceType -eq 'Microsoft.KeyVault/vaults' -Or $resource.ResourceType -eq 'Microsoft.Automation/automationAccounts' -Or $resource.ResourceType -eq 'Microsoft.Automation/automationAccounts/runbooks') { | |
Write-Output "$($resource.Name) - won't be deleted" | |
# instruction 'break' is not supported in Azure PowerShell Automation | |
} | |
else { | |
Write-Output "Deleting - $($resource.Name)" | |
Remove-AzResource -ResourceId $resource.ResourceId -Force | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment