← script library

Automating VM Snapshot Management in VMware vSphere with PowerShell

VMware & vSphereJanuary 6, 2025

Managing snapshots in VMware vSphere is essential for backup and restoration processes. This PowerShell script automates the creation and deletion of snapshots for specified virtual machines (VMs). By using this script, you can efficiently manage VM snapshots, ensuring that your environment is backed up and that old snapshots are removed to free up storage space.

powershell
# Load VMware PowerCLI module
Import-Module VMware.PowerCLI

# Connect to the vSphere server
$vCenterServer = "your_vcenter_server"
$username = "your_username"
$password = "your_password"
Connect-VIServer -Server $vCenterServer -User $username -Password $password

# Define the VMs for snapshot management
$vmNames = @("VM1", "VM2", "VM3") # Replace with your VMs

# Create snapshots for each VM
foreach ($vmName in $vmNames) {
    $vm = Get-VM -Name $vmName
    if ($null -ne $vm) {
        $snapshot = New-Snapshot -VM $vm -Name "Backup-Snapshot-$(Get-Date -Format yyyyMMddHHmmss)" -Description "Snapshot created for backup purposes" -Confirm:$false
        Write-Host "Snapshot created for $vmName with name: $($snapshot.Name)"
    } else {
        Write-Host "VM $vmName not found."
    }
}

# Remove old snapshots
$daysThreshold = 30
foreach ($vmName in $vmNames) {
    $vm = Get-VM -Name $vmName
    if ($null -ne $vm) {
        $oldSnapshots = Get-Snapshot -VM $vm | Where-Object { $_.Created -lt (Get-Date).AddDays(-$daysThreshold) }
        foreach ($snapshot in $oldSnapshots) {
            Remove-Snapshot -Snapshot $snapshot -Confirm:$false
            Write-Host "Removed snapshot: $($snapshot.Name) for VM: $vmName"
        }
    } else {
        Write-Host "VM $vmName not found."
    }
}

# Disconnect from the vSphere server
Disconnect-VIServer -Server $vCenterServer -Confirm:$false

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.