LAST UPDATED: Nov 14 2024

We have a very popular article titled “SOLVED: PowerShell Script To Create VM Snapshots In Azure“. However, it doesn’t address larger clients who have multiple subscriptions.

This article will give you script you need to create and delete snapshots for all Azure subscriptions and Resource Groups within a single tenant.


# Login to Azure
Connect-AzAccount

# Figure out All Subscriptions
$subscriptions = Get-AzSubscription
foreach ($subscription in $subscriptions) {
    Set-AzContext -SubscriptionId $subscription.Id
    
    # Get all resource groups in the current subscription
    $resource_groups = (az group list --query '[].name' --output tsv) -split "`n"
    
    foreach ($resource_group in $resource_groups) {
        Write-Host "Processing resource group: $resource_group"
        
        # Get all VMs in the current resource group
        $vms = (az vm list --resource-group $resource_group --query "[].name" --output tsv) -split "`n"
        
        foreach ($vm in $vms) {
            Write-Host "Creating snapshot of VM: $vm"
            
            # Get the OS disk name of the VM
            $disk_name = (az vm show -d -g $resource_group -n $vm --query "storageProfile.osDisk.name" -o tsv) -split "`n"
            
            # Create a snapshot
            $snapshot_name = "URTech-Snap-$vm-$(Get-Date -Format 'yyyyMMddHHmmss')"
            az snapshot create --resource-group $resource_group --source $disk_name --name $snapshot_name
        }
    }
}


Here is a simplified version of that same script to create snapshots in Azure for all resource groups and all subscriptions you have access to:


Connect-AzAccount
Get-AzSubscription | ForEach-Object {
    Set-AzContext -SubscriptionId $_.Id
    $resource_groups = (az group list --query '[].name' --output tsv) -split "`n"
    foreach ($resource_group in $resource_groups) {
        Write-Host "Processing resource group: $resource_group"
        $vms = (az vm list --resource-group $resource_group --query "[? !starts_with(name, 'WHATEVA-')].[name]" --output tsv) -split "`n"
        foreach ($vm in $vms) {
            Write-Host "Creating snapshot of VM: $vm"
            $disk_name = (az vm show -d -g $resource_group -n $vm --query "storageProfile.osDisk.name" -o tsv) -split "`n"
            $snapshot_name = "URTech-SNAP-$vm-$(Get-Date -Format 'yyyyMMddHHmmss')"
            az snapshot create --resource-group $resource_group --source $disk_name --name $snapshot_name
        }
    }
}

After your work is done and you want to delete those snaps, you can use this command script:


Connect-AzAccount
Get-AzSubscription | ForEach-Object {
    Set-AzContext -SubscriptionId $_.Id
    Get-AzSnapshot -Name "URTech-SNAP-*" | Remove-AzSnapshot -Force
}


0 Comments

Leave a Reply

Avatar placeholder

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