VMware Cloud Community
zhaodiwx
Contributor
Contributor

schedule Remove-snapshot

Hi, I'm New User for PowerCLI,I have a question for schedule Remove-snapshot:

for example:

I have been created a snapshot in PowerCLI for my vm:

$Date = Get-Date -UFormat %Y%m%d

$timechop = Get-Date -Format g

get-vm | where {$_.PowerState -eq "PoweredOn"} | where {$_.Name -match "Linux"} | New-Snapshot -Name "$Date" -Description "PowerCLI Weekly Snapshot at $timechop"

get-vm | where {$_.PowerState -eq "PoweredOn"} | where {$_.Name -match "Linux"} | Get-Snapshot

Name                 Description                    PowerState

----                 -----------                    ----------

20190104             PowerCLI Weekly Snapshot at... PoweredOn

Now the question:

I need to Schedule Remove the Snapshot Before 7 days ago (according the snapshot create day,for example:20190104,autoremove the named"20190104" when the current date is change to 20190111),how to write the scripts?

thanks a lot!

0 Kudos
6 Replies
LucD
Leadership
Leadership

When you say schedule, do you mean the Task Scheduler in the vCenter?


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

0 Kudos
zhaodiwx
Contributor
Contributor

schedule means I want to use windows scheduled task to execute xxx.ps1 file.

0 Kudos
LucD
Leadership
Leadership

The script to remove the snapshots 7 days or older could be something like this

$now = Get-Date

Get-Vm | Get-Snapshot |

where {(New-TimeSpan -Start [DateTime]::ParseExact($_.Name, 'yyyyMMdd', [Globalization.CultureInfo]::CreateSpecificCulture('en-US')) -End $now).TotalDays -ge 7} |

Remove-Snapshot -Confirm:$false

To run this as a Windows scheduled task, see for example How to – run a PowerCLI .ps1 script using the Task Scheduler

If you need more specifics on the scheduled task (like credentials for the Connect-VIServer) let me know.


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

0 Kudos
zhaodiwx
Contributor
Contributor

got it.

Thank you very much.

0 Kudos
MervLAD1
Contributor
Contributor

Is it possible to schedule within vCenter to remove a snapshot? If so, how would the look in powershell?

Is there a "New-VMScheduled Snapshot" command but for deleting a snapshots?

0 Kudos
LucD
Leadership
Leadership

0 Kudos