VMware Cloud Community
deensolea
Contributor
Contributor
Jump to solution

script to check and delete snapshots

hi all, i am trying to use a powercli script to check and delete snapshots from a file. Needed help with error handling; specifically to display if the vm is not reachable when reading from the text file and further if there is no snapshot present, then to display that. Any help would be great.

$VM = Get-VM -Name (get-content servers.txt)
$VM | Get-Snapshot | Remove-Snapshot -RunAsync -Confirm:$false

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try something like this

 Get-Content servers.txt -PipelineVariable vmName |
 ForEach-Object -Process {
    try{
        Get-VM -Name $vmName -ErrorAction Stop
        $snap = Get-VM -Name $vmName | Get-Snapshot
        if ($snap) {
            $snap | Remove-Snapshot -RunAsync -Confirm:$false
        } else {
            Write-Host "No snapshot(s) for VM $vmName"
        }
    }
    catch{
        write-host "VM $vmName not found"
    }
 }


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

2 Replies
LucD
Leadership
Leadership
Jump to solution

Try something like this

 Get-Content servers.txt -PipelineVariable vmName |
 ForEach-Object -Process {
    try{
        Get-VM -Name $vmName -ErrorAction Stop
        $snap = Get-VM -Name $vmName | Get-Snapshot
        if ($snap) {
            $snap | Remove-Snapshot -RunAsync -Confirm:$false
        } else {
            Write-Host "No snapshot(s) for VM $vmName"
        }
    }
    catch{
        write-host "VM $vmName not found"
    }
 }


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

deensolea
Contributor
Contributor
Jump to solution

@LucD  thank you, as always works perfectly.

0 Kudos