Open In App

Microsoft Azure – Deletion of Snapshots using PowerShell Script

Improve
Improve
Like Article
Like
Save
Share
Report

Snapshot is a kind of read-only copy of the existing Azure VM disk of either OS disk or data disk. This snapshot is used as a backup for VM in case of any failure to retrieve the backup of a VM in case of crashes.

In this article, you will learn about the deletion of all the Snapshots within the Subscription from all the Resource Groups at once using Azure PowerShell commands in the form of snippets. Before implementing the process let’s see what is snapshot.

Why do we need to delete the Azure snapshot?

In case of unwanted resources, we should delete the bulk snapshots as it will cost the resources for storing. So deleting unwanted snapshots in azure will save a lot of costs as it is cost-effective.

The following Remove-AzSnapshot cmdlet removes a snapshot in Azure. 

Syntax:

$Name = "Add_Snapshot_Name_here"
$ResourceGroupName = "Add_Resource_Group_Name_here"

Remove-AzSnapshot -ResourceGroupName $ResourceGroupName -SnapshotName $Name -Force;

Here in the $Name represents the Azure Snapshot Name and $ResourceGroupName represents the Resource Group in which the Snapshot is located.

Note: Add Resource Locks to the Snapshots to skip the deletions.

Implementation:

Step 1: Log in to Azure Portal

Step 2: Access the Azure Cloud Shell and Select PowerShell Console

Step 3: Create a New file using the touch command 

touch remove-snapshots.ps1

use the following command to open the file in editor mode

code ./remove-snapshots.ps1

then, paste the below PowerShell Snippet code into that file and save the file.

$SubscriptionName = "_add_subscription_name"

Set-AzureRmContext -SubscriptionName "$SubscriptionName" | Out-Null

$RGs = Get-AzureRMResourceGroup

foreach ($RG in $RGs) {

    $Snapshots = Get-AzSnapshot -ResourceGroupName $RG.ResourceGroupName

    foreach ($Snapshot in $Snapshots) {

        $Name = $Snapshot.Name
        $ResourceGroupName = $Snapshot.ResourceGroupName
        
        Remove-AzSnapshot -ResourceGroupName $ResourceGroupName -SnapshotName $Name -Force;
        Write-Output "Deleted $Name - $ResourceGroupName"
    }
}

Refer Image:

Step 4: To run the above PowerShell Script use the following command

./remove-snapshots.ps1 

The output looks like the following below:

Reference:


Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads