Read about escaping rules:
- in command line (
&
ampersand character already escaped in double-quoted string)
- in powershell (escape
""
embedded double quotes)
- in schtasks.exe (escape
\"
embedded double quotes: learn by example in this description)
Tested in following batch script. Note that ;pause
in -command
argument allows observing powershell script results for debugging purposes; auxiliary ST*
variables are used merely for better readability (STn
=name, STe
=executable, STc
=command, STp
=parameter):
@ECHO ON
@SETLOCAL EnableExtensions
set "STn=MyTaskName"
set "STe=%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe"
set "STc=D:\PShell\SO\36493932 with spaces.ps1"
set "STp=D:\bat\a b\testfile.txt"
schtasks.exe /create /f /tn "%STn%" /tr "%STe% -command & \"\"\"%STc%\"\"\" \"\"\"%STp%\"\"\";pause" /SC ONCE /SD 10/04/2016 /ST 11:00
@rem /RU %USERDOMAIN%\%username% /RP
@timeout /T 3 >NUL
schtasks /Run /TN "%STn%"
@pause
schtasks /End /TN "%STn%"
and following powershell
script (although this does not matter):
param([string] $InObject = $MyInvocation.InvocationName)
"{0} {1}" -f "listing:", "$InObject"
Get-Content "$InObject"
Output (note that powershell
script output is visible in another window):
==> D:\bat\SO\36472103.bat
==> set "STn=MyTaskName"
==> set "STe=C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe"
==> set "STc=D:\PShell\SO\36493932 with spaces.ps1"
==> set "STp=D:\bat\a b\testfile.txt"
==> schtasks.exe /create /f /tn "MyTaskName" /tr "C:\Windows\system32\WindowsPowerShell\v1.
0\powershell.exe -command & \"\"\"D:\PShell\SO\36493932 with spaces.ps1\"\"\" \"\"\"D:\bat\
a b\testfile.txt\"\"\";pause" /SC ONCE /SD 10/04/2016 /ST 11:00
SUCCESS: The scheduled task "MyTaskName" has successfully been created.
==> schtasks /Run /TN "MyTaskName"
SUCCESS: Attempted to run the scheduled task "MyTaskName".
Press any key to continue . . .
==> schtasks /End /TN "MyTaskName"
SUCCESS: The scheduled task "MyTaskName" has been terminated successfully.
==>