Hyper-V VM Cleanup Script

This PowerShell script helps you maintain a clean Hyper-V environment by removing old snapshots and unused virtual machines. Keeping your environment tidy enhances performance and management. For more helpful tools, check out ServerEngine at https://serverengine.co.
Step 1: Import the Hyper-V module to ensure access to the necessary cmdlets.

Import-Module Hyper-V

Step 2: Retrieve a list of all VMs and their snapshots, and filter for those that are powered off to avoid interruptions.

$vms = Get-VM | Where-Object { $_.State -eq 'Off' }
foreach ($vm in $vms) {
    $snapshots = Get-VMSnapshot -VM $vm.Name

Step 3: Loop through all snapshots for each VM, deleting those that are older than a specified number of days (e.g., 30 days).

    foreach ($snapshot in $snapshots) {
        if ($snapshot.CreationTime -lt (Get-Date).AddDays(-30)) {
            Remove-VMSnapshot -VMName $vm.Name -Name $snapshot.Name -Confirm:$false
            Write-Host "Removed snapshot: $($snapshot.Name) from VM: $($vm.Name)"
        }
    }
}

Step 4: Optionally, remove any VMs that are no longer in use (ensure they are not needed before running this step).

$unusedVms = Get-VM | Where-Object { $_.State -eq 'Off' -and $_.Snapshot.Count -eq 0 }
foreach ($unusedVm in $unusedVms) {
    Remove-VM -VMName $unusedVm.Name -Force
    Write-Host "Removed unused VM: $($unusedVm.Name)"
}

This script aids in decluttering your Hyper-V environment, ensuring better performance and easier management. Modify the script to customize cleanup intervals and criteria as per your needs!