Wednesday, November 30, 2016

How to run Powershell script as a scheduled task

Normally, we can execute a PowerShell script by typing ./ followed by the name of the script and if want to run a script on a scheduled time then we can schedule it with Windows Task Scheduler.

Lately, I had issues while scheduling an script as scheduled task so thought of making this note for future reference.

As we all would be aware, before calling any PowerCLI cmdlet we should load PoweCLI Snapin to powershell first without which PowerShell will not recognize any of the PowerCLI cmdlets. There are two ways to do this,

#1. Add the following line to the top of each PowerCLI script you will be running as a scheduled task,

add-pssnapin VMware.VimAutomation.Core

Now while creating the scheduled task, under Action option, pass the script execution command as follows,

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe "& 'C:\Script.ps1'"

you can also use this,  C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -file "C:\Script.ps1"

#2. This method runs the PowerCLI Console file before it runs your script. This will enable the PowerCLI snapin for you and there is nothing to add to the scripts.

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1  "& 'C:\Script.ps1'"

Before using any of this method first we need to ensure it will work by running them from a cmd prompt. During testing we may aslo use the –noexit switch to see any errors arising from the operation.

For detailed info about runing Powershell script as a scheduled task, you can checkout Dmitry's related blog post, HERE, Alan Renouf's post, HERE and this blog post.

That's it... :)

No comments:

Post a Comment