Question

I've created a script that creates a new snapshot in a VM and then deletes all but the 6 newest snapshots in that VM. I want to find a way to make my script check for errors and confirm that everything is working fine, but have never used try/catch in Powershell before and was curious if anyone could guide me with what I'm doing wrong:

$server = $args[0]
$date = get-date
try{
    new-snapshot -vm $server -name "Auto Created via Powershell" -description $date
}
catch{
    [system.exception]
    "Not finding"}  
get-snapshot -vm $server | sort -property created -desc | select -skip 6 | foreach-object{remove-snapshot $_ -confirm:$false}
if (get-snapshot -vm $server | select -first 6){
    write-host "script is keeping current 6 as expected"
}

The first part of my code where I'm creating a new snapshot works fine, the issue is in the second part where I want to confirm that all but the 6 newest snapshots were deleted. At the moment I'm trying to use an if statement to confirm, however I'm not getting any output from my if statement. Regardless, I was curious if there is a better method to do the second part of my script to confirm, rather than using an if statement to confirm that the script is keeping the current 6 newest snapshots.

Thanks!

Was it helpful?

Solution

So try this out think it might work .

 $server = $args[0]
    $date = get-date
    try{
        new-snapshot -vm $server -name "Auto Created via Powershell" -description $date
       }
    catch{
          [system.exception]
         "Not finding"}  

    get-snapshot -vm $server | sort -property created -desc | select -skip 6 | foreach-object{remove-snapshot $_ -confirm:$false}

$ListOfVms = get-snapshot -vm $server

if ($ListOfVms.count -eq 6){
    write-host "script is keeping current 6 as expected"
    }

This should count the number of vms and if it is equal to 6 write the text you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top