SOLVED: Simple PowerShell Script To Take Snapshots of Azure VMs

script take azure snapshotsscript take azure snapshots

We have published a number of relatively complex powershell cloud shell scripts to take snapshots of virtual machines. This is a simple script that is useful for those who are working with a single resource group in a single subscription, like most SMB’s.

If you are running this via PowerShell on your desktop or server, you will need to connect to your Azure account first:

# Login to Azure IF Using PowerShell on Desktop PC
Connect-AzAccount

If you are running this from CloudShell in the Azure Portal, you can skip that step


# List of VM names
$vmNames = @(“***VM-HOST-NAME1***“, “***VM-HOST-NAME2***“, “***VM-HOST-NAME3***”, “***VM-HOST-NAME4***“, “***VM-HOST-NAME5***“)

# Set the subscription context
Set-AzContext -SubscriptionName "****YOUR-SUBSCRIPTION-NAME-HERE****"

# Set the resource group name
$resourceGroupName = "****YOUR-RESOURCE-GROUP-NAME-HERE****"

# Verify the resource group exists
$resourceGroup = Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if (-not $resourceGroup) {
    Write-Error "Resource group '$resourceGroupName' could not be found."
    return
}

# Loop through each VM and take a snapshot
foreach ($vmName in $vmNames) {
    # Get the VM
    $vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName

    # Get the OS disk
    $osDisk = $vm.StorageProfile.OsDisk

    # Create a snapshot configuration
    $snapshotConfig = New-AzSnapshotConfig -SourceUri $osDisk.ManagedDisk.Id -Location $vm.Location -CreateOption Copy

    # Create the snapshot with the prefixed name
    $snapshot = New-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName "URTectDotCa-$vmName-snapshot" -Snapshot $snapshotConfig

    Write-Output "Snapshot for $vmName created successfully with name IanM-PreDiskExp-$vmName-snapshot."
}

We hope this helps.


Published by
Ian Matthews