Running PowerShell Scripts from Windows Task Scheduler

Sometimes, we write scripts that we want to schedule.  For example, I recently put together a small script that checks an environment for Snapshots that are older than 7 days and then emails the sys admins a report if it finds any.  Alan Renouf put together a quick guide on how to run PowerShell scripts with Windows Task Scheduler back in 2009, but I ran into a hiccup while trying to use that procedure the other day.

Alan suggests two possible methods for accomplishing this task.  One involves editing your scripts to add the required PS Snapins and the other involves launching the PowerShell session from a pre-configured Console File.  I decided that I’d had enough of messing around with Add-PSSnapin, so I decided to experiment with the PowerShell Console option.  The example syntax that he provides is basically:

Powershell.exe –PSConsoleFile myConsole.psc1 & myScript.ps1


Which didn’t exactly work for me.  When I executed this at a command line, it started PowerShell and then, after I quit PowerShell, opened up my script in Notepad.  Perhaps it was just the server on which I was trying to schedule the task, but I found that I needed to use this syntax:

Powershell.exe –PSConsoleFile myConsole.psc1 -file myScript.ps1


That syntax successfully opened the PowerShell session with my Console settings and executed the specified script.  Of course, this is assuming that you know what a Console settings file (that .psc1 file in the example) is.  I didn’t before I tried to use one.  Apparently, it’s just a very simple XML file that specifies a particular version of PowerShell as well as a collection of Add-Ins and Modules that must be loaded.  In fact, if you look at your PowerCLI shortcut (go ahead, open its properties), you’ll see that it uses that same –PSConsoleFile syntax to point at a nice simple vim.psc1 file (as well as running an initialization script).  That’s why that PowerCLI icon automatically loads all of those VMware cmdlets that we all know and love.

Anyway, how do you create one?  Well, I suppose that you could do so by hand… but who wants to introduce that element of human error to their environment?  Fortunately, there’s an easy way.  Open up a PowerShell session and add whatever Snap-Ins you want, then use this command to export those settings to a Console file:

Export-Console myConsole.psc1


Easy peasy pudding and gherkins.

Comments

Popular posts from this blog

Clone a Standard vSwitch from one ESXi Host to Another

PowerShell Sorting by Multiple Columns

Deleting Orphaned (AKA Zombie) VMDK Files