PowerShell add Task to run PowerShell script with parameters
Asked Answered
R

3

4

I am trying add a Task to the Task Scheduler from a PowerShell script that will run a PowerShell script with parameters.

The spaces in the file path are conflicting with the necessary quotes surrounding the whole command, and SCHTASKS converts ' to " so I can't encapsulate properly.

$command = "PowerShell \`"& 'C:\ProgramFiles (x86)\MyDir\MyScript.ps1' $myStringParam $myBooleanParam\'"" 
Write-Host $command # This outputs: PowerShell \"& 'C:\Program Files (x86)\MyDir\MyScript.ps1' Cat 0\"  
SCHTASKS /Create /TN "MyTask" /TR "$command" /SC DAILY /ST 01:30:00 /RL Highest /EC ScriptEvents /RU SYSTEM

but Task Scheduler shows Actions as:

PowerShell "& "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0"

The " and " cancel each other out because ' is always switched to " here, thus task fails.

Rotation answered 23/5, 2013 at 21:10 Comment(0)
R
3

Solved it by using \" as the inner quotes. Had to swap ' with \\\`" in PowerShell script

$command = "PowerShell \`"& \\\`"C:\ProgramFiles (x86)\MyDir\MyScript.ps1\\\`" $myStringParam $myBooleanParam\'"" 

So Task Scheduler shows

PowerShell "& \"C:\Program Files (x86)\MyDir\MyScript.ps1\" Cat 0"
Rotation answered 24/5, 2013 at 14:52 Comment(0)
K
3

Try using the -File parameter of powershell.exe to specify the script to run and just add the parameters of the script at the end

powershell.exe -File "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0

UPDATE

Boolean and Switch parameters seem to be a problem with -File. This will work:

powershell.exe "C:\Program Files (x86)\MyDir\MyScript.ps1" Cat 0
Kirsten answered 23/5, 2013 at 21:31 Comment(2)
Tried that many times, doesn't work because then PowerShell can't translate the 0 (or $false) to boolean from the string.Rotation
@Brent: Seems to be a known problem. Updated my answer with a fixKirsten
R
3

Solved it by using \" as the inner quotes. Had to swap ' with \\\`" in PowerShell script

$command = "PowerShell \`"& \\\`"C:\ProgramFiles (x86)\MyDir\MyScript.ps1\\\`" $myStringParam $myBooleanParam\'"" 

So Task Scheduler shows

PowerShell "& \"C:\Program Files (x86)\MyDir\MyScript.ps1\" Cat 0"
Rotation answered 24/5, 2013 at 14:52 Comment(0)
T
0

Use the -command parameter for powershell:

What you would execute in your powershell without task sceulder:

C:\Scripts\mypsscript.ps1 -parameter 'nice value'

What you give the task sceduler:

Programm to run: Powershell

Arguments:

-Command "& C:\Scripts\mypsscript.ps1 -parameter 'nice value'"
Trenchant answered 16/3, 2017 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.