VMware Cloud Community
MGandhi
Contributor
Contributor

Check if Snapshot Exists statement

I need help with the script to check if Snapshot name exists then Exit the script and don't create a new snapshot, If $SnapshotName does not exist then create it.

$VCServer='XYZ'

$Snapshot='test'

Connect-VIServer $VCServer

$vm= Get-VM -Name $VMName.Split(".")[0]
$ExitingSnapshot= get-snapshot -vm $vm -Name $Snapshot

if ($ExitingSnapshot = $snapshot )  {write-output "Requested snapshot name already exists on VM";exit 0}
else {New-Snapshot -VM $vm -Name $Snapshot -Description "test Snapshot"}

Thanks for any help

Reply
0 Kudos
2 Replies
LucD
Leadership
Leadership

You retrieve the snapshot and specify the -ErrorAction  parameter, that way you won't get an error message when the snapshot doesn't exist.

Then you test if the Get-Snapshot returned an object or not.

If the variable $ExistingSnapshot is empty the expression will evaluate to $false, otherwise $true

$VCServer='XYZ'

$Snapshot='test'

Connect-VIServer $VCServer

$vm= Get-VM -Name $VMName.Split(".")[0]
$ExitingSnapshot= get-snapshot -vm $vm -Name $Snapshot -ea SilentlyContinue

if ($ExitingSnapshot)  {write-output "Requested snapshot name already exists on VM";exit 0}
else {New-Snapshot -VM $vm -Name $Snapshot -Description "test Snapshot"}


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

Reply
0 Kudos
MGandhi
Contributor
Contributor

Thank you!!! This resolved my issue.

Reply
0 Kudos