Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,295 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
try {
Write-Output "Logging in to Azure..."
Connect-AzAccount -Identity
} catch {
Write-Error -Message $_.Exception
throw $_.Exception
}
# Specify the target resource group for storing snapshots
$targetResourceGroup = "snapshot-RG"
# Calculate the date 4 days ago
$fourDaysAgo = (Get-Date).AddDays(-0)
# Get snapshots in the target resource group
$snapshotsToDelete = Get-AzSnapshot -ResourceGroupName $targetResourceGroup
# Loop through each snapshot
foreach ($snapshot in $snapshotsToDelete) {
$snapshotName = $snapshot.Name
$snapshotCreationTime = $snapshot.TimeCreated
Write-Output "Checking snapshot $snapshotName created on $snapshotCreationTime"
# Compare the creation time with fourDaysAgo
if ($snapshotCreationTime -lt $fourDaysAgo) {
Write-Output "Deleting snapshot $snapshotName as it is older than 4 days"
#if ($snapshotUsage -eq "OSDisk" -and $snapshotCreationTime -lt $fourDaysAgo) {
#Write-Output "Deleting OS disk snapshot $snapshotName as it is older than 4 days"
Remove-AzSnapshot -ResourceGroupName $targetResourceGroup -SnapshotName $snapshotName -Force
}
}