Pass Powershell parameters within Task Scheduler

I recommend scheduling the task to use the -File parameter rather than -Command. Example:

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments (optional): -NoProfile -ExecutionPolicy Bypass -File "Scheduled-ServiceRestart.ps1" -ErrorLog "ScriptErrors.txt" -Services "foo1","foo2" -MaxSize 5MB

Start in (optional): C:\Users\<username>\Documents\Scripts

You can specify the starting directory for the script in the "Start in" property for the task and avoid the lengthy path names to the script and log files. (Note that I am assuming you are running a copy of the script on the local computer, not over the network, which adds potential complications and possibilities for failure.)


As far as a literal answer to the question: Likely you need to add single quotes to surround your script location, otherwise it will try to interpret special characters/backslashes as escapes.

Ex:

-Command "& '\ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1' ...

You could also add some basic logging in your powershell script to ensure that it is actually starting.

I use the "-Command &" style in production Powershell scheduled tasks & they work fine provided the strings are formatted properly.


The function needs to be imported first. I would recommend saving the function as a module and placing it in the modules folder in either system32 or program files. This way, when powershell is launched, it will automatically import your function.

After you do that, the task scheduler is very simple.

Program/Script

Powershell

Add arguments(optional):

-Command &{ServiceRestart -ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt' -Services 'foo1','foo2' -MaxSize '5MB'}

Apparently, when using Scheduled Tasks, the choice of quotes makes a huge difference. Try this for your arguments:

-Command "& '\\ServerName\C$\Users\...\Documents\Scripts\Scheduled-ServiceRestart.ps1' -ErrorLog '\\ServerName\C$\Users\...\Documents\log\ScriptErrors.txt' -Services 'foo1','foo2' -MaxSize '5MB'"