-1

Im new to powershell and i want to create a script to take a snapshot of all the running vm's and delete the snapshots that have more than lest say 5 days. What i have is this:

$Time = 5 
$VMs = Get-VM | Where-Object {$._State –eq 'Running'}
foreach($VM in $VMs){
$Snapshots = Get-VMSnapshot $VM

foreach($Snapshot in $Snapshots){

    if ($snapshot.CreationTime.AddDays($Time)) {
        Remove-VMSnapshot $Snapshot

    } 
}

Checkpoint-VM $VM
}

But is not workin.

  • Can you elaborate on "But is not workin"? Where does your script seem to stop working – Martyn C May 17 '16 at 20:53
  • 1
    if ($snapshot.CreationTime.AddDays($Time) -le (Get-Date)) { you need to use conditional expression in if. Although $snapshot.CreationTime.AddDays($Time) is not boolean value, if command would evaluate it to true… – JosefZ May 17 '16 at 21:46
  • 1
    And typo in Where-Object {$._State –eq 'Running'} should be $_.State instead of $._State. Please follow @MartynC and edit your question. It's a bit unclear as currently written. – JosefZ May 17 '16 at 22:00
  • Well spotted @JosefZ, I hadn't even looked at the script yet 😀 – Martyn C May 17 '16 at 22:04
  • @JosefZ i fix the typos and add (get-date) in the last if and now is working like a charm. i will post the script with the fixes. Thanks a lot for the help. – guelo May 19 '16 at 20:14
0

After reading some comments I was able to solve the issue I was having.The script will look like this:

$Days = 4 

$VMs = Get-VM | Where-Object {$_.State –eq 'Running'}
foreach($VM in $VMs){
$Snapshots = Get-VMSnapshot $VM

foreach($Snapshot in $Snapshots){

    if ($snapshot.CreationTime.AddDays($Days) -lt (get-date)) {
        Remove-VMSnapshot $Snapshot

    } 
}

Checkpoint-VM $VM
}

Notice that i fix the typo and also add the (get-date) part so I can compare the time with my variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.