Wednesday, July 14, 2010

Scheduling a PowerShell task

I wanted to schedule a PowerShell script to run every night but ran into some problems. Whatever I tried, the scheduled task would either finish instantly without running the script or would hang indefinitely, also without running the script. The following things didn't work:



Action: Start a program

Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): myscript.ps1
Start in (optional): c:\scripts

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): c:\scripts\myscript.ps1
Start in (optional): c:\scripts

Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -noexit -command &"c:\scripts\myscript.ps1"
Start in (optional): c:\scripts

Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -noexit -command " &'c:\scripts\myscript.ps1' "
Start in (optional): c:\scripts


I also tried variations with just calling powershell.exe since the path is in env. variables, I also tried to call the 64bit version at C:\Windows\SysWOW64\WindowsPowerShell\v1.0\poweshell.exe.

Nothing worked.

In the end, I created a myscript.bat in the c:\scripts and put this in it:


powershell.exe ".\myscript.ps1"

Then my scheduled task action was

Program/script: c:\scripts\myscript.bat
Start in (optional): c:\scripts

Hope this helps.