UPDATED 11/09/2016 @11:39 PM EST

It’s 2:55 AM and I’m about to crash.  Been writing and testing PowerShell code to automate some interesting Azure environment builds.  In the process of building, testing, tearing down and repeating, I needed a quick way to reset or “clean” my Azure subscription between runs.

This requires me to keep one resource group (yes, this is ARM related) from being wiped out, because it houses some template VHD’s and so on.  Anyhow, this code works from PowerShell ISE best (because ISE, unlike the regular PS console, maintains the credential object in memory during each session).  Anyhow, I thought you might find it useful if you don’t already have a better option… cheers!

Option A – White-listing

# array of resource groups to keep (white list)
$ProtectedRGNames = ("Templates")

Write-Output "checking if session is authenticated..."
if ($azCred -eq $null) {
  $azCred = Login-AzureRmAccount
  $accountID = $azCred.Context.Account.Id
  $subscriptionID = $azCred.Context.Subscription.SubscriptionId
  $tenantID = $azCred.Context.Tenant.TenantId
}
else {
  Write-Output "authentication already confirmed."
}
#
$RgList = Get-AzureRmResourceGroup
Foreach ($rg in $rgList) {
  $rgn = $rg.ResourceGroupName
  if ($ProtectedRGNames.Contains($rgn)) {
    Write-Host "skipping: $rgn"
  }
  else {
    Write-Output "removing: $rgn"
    Remove-AzureRmResourceGroup -Name $rgn -Force
  }
}

Option B – Blacklisting

# wildcard match for RGs to delete (blacklist)
$KeepRGNames = "test*"
Write-Output "checking if session is authenticated..."
if ($azCred -eq $null) {
  $azCred = Login-AzureRmAccount
  $accountID = $azCred.Context.Account.Id
  $subscriptionID = $azCred.Context.Subscription.SubscriptionId
  $tenantID = $azCred.Context.Tenant.TenantId
}
else {
  Write-Output "authentication already confirmed."
}

$rgList = Get-AzureRmResourceGroup | ?{$_.ResourceGroupName -ilike $KeepRGNames}
#
foreach ($rg in $rglist) {
  $rgn = $rg.ResourceGroupName
  Write-Output "removing: $rgn"
  Remove-AzureRmResourceGroup -Name $rgn -Force
}

Just another option. 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s