i want automation script to delete only os disk snapshot older than 4 days

Chinnamma K K 0 Reputation points
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

Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,143 questions
{count} votes