Skip to content

Instantly share code, notes, and snippets.

@BelRarr
Created January 3, 2020 18:28
Show Gist options
  • Save BelRarr/b6f725001d362553b61ab433d549fadd to your computer and use it in GitHub Desktop.
Save BelRarr/b6f725001d362553b61ab433d549fadd to your computer and use it in GitHub Desktop.
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)
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