Scheduled task to run a PowerCLI script (and delete a named snapshot)

I had occasion recently to delete a snapshot at a certain time. It’s easy enough to schedule the snapshot using the vSphere Client and built-in functions, but then, how to delete it on a schedule? Enter PowerCLI and the Windows Task Scheduler.

There was a VMTN forum post by Duncan Epping (@DuncanYB) that suggested using the generic form Get-VM | Get-Snapshot | Remove-Snapshot. This worked a charm for me and I put it into the following script.

Connect-VIServer -Server localhost -User domain\username -Password password
$vm = ‘server-name’
$snapshot_name = ‘snapshot-name’
$snapshot = (Get-VM -Name $vm | Get-Snapshot -Name $snapshot_name)
Remove-Snapshot -Snapshot $snapshot -Confirm:$false


Since this script is run from the vCenter server itself, I used localhost in Connect-VIServer. Deleting the snapshot wasn’t so hard, but getting Alan Renouf’s solution in his blog post gave me a fit because I didn’t pay close enough attention.

As you can imagine, it’s important to know *where* PowerCLI is installed on the machine executing the script to that the system can instantiate it. In my case, it was installed in D:\Program Files (x86), so I had to modify Alan’s script to accommodate my installation.

I used this path and the following lines when using Windows Task Scheduler to execute the PowerCLI script. Note the placement of all the quotation marks.

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile “D:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1” “& “D:\Powershell_Script\DeleteSnapshot.ps1“”

The first directory path, in yellow, is the path to the PowerShell executable. The second path, in blue, is directed at the PowerCLI installation, and finally, the last path, in orange, points to the script.

When creating the scheduled task, ensure only the first path goes in the “Program/script:” edit box and everything after “-PSConsoleFile” goes into the “Add arguments (optional)” edit box.


Of course, if PowerCLI is installed in a different path, change the blue part above. And replace the path to your script in the orange part above, too.



One Comment on “Scheduled task to run a PowerCLI script (and delete a named snapshot)”

  1. Adam says:

    Extremely helpful, tried other suggestions and none worked!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s