To remove snapshots from all VMs that have more than two snapshots using VMware PowerCLI (PowerShell module for managing VMware environments), you can use the following PowerShell script as a starting point:
# Connect to your vCenter Server
Connect-VIServer -Server YourVCenterServer -User YourUsername -Password YourPassword
# Get all VMs with more than two snapshots
$VMs = Get-VM | Where-Object { $_.ExtensionData.Snapshot.RootSnapshotList.Count -gt 2 }
# Loop through VMs and remove snapshots
foreach ($VM in $VMs) {
$Snapshots = $VM | Get-Snapshot
$Snapshots | Sort-Object -Property Created -Descending | Select-Object -Skip 2 | Remove-Snapshot -Confirm:$false
Write-Host "Snapshots removed from $($VM.Name)"
}
# Disconnect from the vCenter Server
Disconnect-VIServer -Server * -Confirm:$false
Please note the following points about this script:
- Replace
YourVCenterServer,YourUsername, andYourPasswordwith your actual vCenter Server details. - The script retrieves all VMs with more than two snapshots using
Get-VMand filters them usingWhere-Object. - The snapshots are sorted by their creation date in descending order, and the two most recent snapshots are skipped (to retain the two most recent snapshots).
- The
-Confirm:$falseparameter is used withRemove-Snapshotto avoid confirmation prompts for each snapshot removal.
Before running this script, make sure you have VMware PowerCLI installed and that you are using it in a controlled environment, as removing snapshots can impact VMs and their data. Test the script on a smaller scale or non-production environment to ensure it behaves as expected.
Always ensure you have backups and a proper understanding of the impact of snapshot removal on your VMs before performing such operations in a production environment.