← script library

Hyper-V VM Cleanup Script

Hyper-VJanuary 10, 2025

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.

powershell
Import-Module Hyper-V

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

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)"
        }
    }
}

$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)"
}

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.