I usually use FunctionApp function with a timer to run maintenance type of scripts but this script can also be used manually. This can be helpful if you still need to store a disk for a couple days or longer before deleting it. Typically, we will delete Personal Azure Virtual Desktop virtual machines and NICs, but keep the disk for 5 days incase a user still needed their VM or forgot to move a file to OneDrive. Changing the SKU/Performance will help reduce your costs.
This script will get all disks and check if unattached then change the disk performance to Standard HDD only if unattached.
Connect-AzAccount
# Get all the disks in the subscription
$disks = Get-AzDisk
# Filter the disks that are not attached to any VM
$unattachedDisks = $disks | Where-Object {$_.ManagedBy -eq $null}
# Change performance SKU to Standard_LRS for each unattached disk
foreach ($disk in $unattachedDisks) {
Try {
# Update the disk's SKU
$disk.Sku = [Microsoft.Azure.Management.Compute.Models.DiskSku]::new('Standard_LRS')
# Update the disk in Azure
$updatedDisk = $disk | Update-AzDisk
# Display the updated disk details
Write-Host "Disk '$($updatedDisk.Name)' in resource group '$($updatedDisk.ResourceGroupName)' would be updated to use Standard_LRS."
}
Catch {
# Display the error message
Write-Warning "Error updating disk '$($disk.Name)' in resource group '$($disk.ResourceGroupName)': $($_.Exception.Message)"
}
}
# Display the unattached disks
if ($unattachedDisks) {
Write-Host "Unattached disks found:"
$unattachedDisks | Format-Table Name, ResourceGroupName, Location, DiskSizeGB, Sku
} else {
Write-Host "No unattached disks found."
}