Clear resources in Azure subscription

Christmas is coming, so it’s good time to clear resources in Azure subscription :).
Today’s article will show you how easly do it via Powershell.

To make long story short – script is scanning for all resource groups in selected subscription.
For each of the resource group it displays all resources and user can decide if whole resource group should be removed or not.

Script:

Login-AzureRmAccount 

$Subscriptions = Get-AzureRmSubscription 
$Subscriptions | Format-Table -Property Name, SubscriptionId, State

$SubscriptionID = Read-Host "Provide ID of the subscription which should be cleaned"
Try
{
    $Sub = Get-AzureRmSubscription -SubscriptionId $SubscriptionID -ErrorAction Stop| Select-AzureRmSubscription
        
}
Catch
{
    Write-Host "Subscription with ID $SubscriptionID can no be found, script will be stopped!" -ForegroundColor Red
    Break;
}
 
$ResourceGroups = Get-AzureRmResourceGroup
if($ResourceGroups)
{
    foreach($RG in $ResourceGroups)
    {

        $ResourceGroup = $RG.ResourceGroupName

        Write-Host $ResourceGroup -ForegroundColor Green 
        Write-Host "------------------------------------------------------`n" -ForegroundColor Green
        $Resources = Find-AzureRmResource -ResourceGroupNameContains $ResourceGroup

        if($Resources)
        {
            $Resources | Format-Table -Property Name, ResourceName, ResourceType, Tags
        }
        else
        {
             Write-Host "No resources find in RG $RG"
        } 
        Write-Host "`n------------------------------------------------------" -ForegroundColor Green
    
        $RemoveRG = Read-Host "Would you like to remove resource group $ResourceGroup with all resources? (yes/no)"
        if($RemoveRG -eq "yes")
        {
            Remove-AzureRmResourceGroup -Name $ResourceGroup -Force
            Write-Host "`nResource group " $ResourceGroup " has been removed."
            Write-Host "------------------------------------------------------" -ForegroundColor Green
        }
        else
        {
            Write-Host "`nResource group " $ResourceGroup " was skipped."
            Write-Host "------------------------------------------------------" -ForegroundColor Green
        }
    }
}
else
{.Na
    Write-Host "0 resource groups have been found in " $Sub.Subscription.Name "subscription!"
}

Output:

Attention!

Powershellbros do not take responsibility for any damage caused by running this script.
Before running it, ensure that you are removing resources from proper subscription.

I hope it will be usefull for some of you and you will clear resources in Azure subscription before New Year 😉
Enjoy and Merry Christmas!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.