#28 Schedule PowerCLI cmdlet

Reading Time: 1 minute

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 <em>vCenter_hostname</em> -User <em>Administrator</em> -Password <em>password</em>
$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 "" -subject "VM clone deleted" \ 
-body $Report -smtpServer $MailSmtpServer 

Disconnect-VIServer <em>vCenter_hostname</em> -Confirm:$false</pre>

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.

#89 Visual C#: Weather Gadget – WUnderK
#24 System uptime, age of Windows install using Visual C++
#27 PowerShell, WSUS, and SharePoint
There are currently no comments.