Home ProgrammingPowerShell PowerShell: Schedule PowerCLI cmdlet

PowerShell: Schedule PowerCLI cmdlet

by Kliment Andreev
5.2K views

Scheduling PowerCLI cmdlet is a bit different than scheduling standard PowerShell scripts. Here is an example of a script that deletes a cloned VM and sends an e-mail using the SMTP settings from vCenter.

add-pssnapin VMware.VimAutomation.Core

Connect-VIServer vCenter_hostname -User Administrator -Password password
$vCenterSettings = Get-View -Id 'OptionManager-VpxSettings' 

$MailSender = ($vCenterSettings.Setting | Where-Object { $_.Key -eq "mail.sender"}).Value
$MailSmtpServer = ($vCenterSettings.Setting | Where-Object { $_.Key -eq "mail.smtp.server"}).Value  

Remove-VM <em>VM-TO-BE-DELETED</em> -DeleteFromDisk -Confirm:$false

$Report = "Old clone deleted, new cloning will start in 5 minutes."

Send-MailMessage -from $MailSender -to "[email protected]" -subject "VM clone deleted" \ 
-body $Report -smtpServer $MailSmtpServer 

Disconnect-VIServer vCenter_hostname -Confirm:$false

Save this file as C:\folder\script.ps1 or whatever you want to name it, and start the Windows scheduler. Make sure that Run whether user is logged on or not is selected under the General tab. Configure the settings under the trigger tab and then create a new action under Actions tab. For program/script, add C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe and for the arguments, add “& ‘c:\folder\script.ps1’“. And, that’s it.
NOTE: Pay special attention on the quotes. It starts with double quote, ampersand, space, single quote, the full path to the script, single quote, and finally double quote.
If the script doesn’t work, it’s probably because you have a newer version of PowerCLI. Use Import-Module -Name VMware.PowerCLI instead of add-pssnapin VMware.VimAutomation.Core.

Related Articles

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More