lets say I have a myScript.ps1
file, that at some point needs to run native commands/binaries. its content is:
set-content -path "c:\temp\test.text" -value "hello world"
. 'C:\temp\myCliTool.exe'
If I manually, create a task in task scheduler and set the "actions" tabs to
"C:\Program Files\PowerShell\7\pwsh.exe"
-NoProfile -ExecutionPolicy Bypass -command "& {. 'C:\temp\myScript.ps1'}"
The ps1 script runs fine, the test.txt
file is created. Also, the native command it needs to fully perform its task runs
But if I run the same script, again via task scheduler but in the "actions" tab, make a slight change:
"C:\Program Files\PowerShell\7\pwsh.exe"
-NoProfile -ExecutionPolicy Bypass -file 'C:\temp\myScript.ps1'
The script does not appear to run. the test.txt
file is not created. Also, the native command does not run.
This issues does not occur if I attempt to run pwsh by other means, for example cmd.
I am thinking task scheduler is at fault here. I have spent all day fixing its "features", like the Path Env variable not being available under task scheduler calls.
Trying to figure out the issue of pwsh -file
calls has proven fruitless, I tried redirecting potential errors that might occur in the PowerShell script to a text file, but I could not fully figure that out.
Am on pwsh 7.4 and windows 11
In no-shell invocation contexts on Windows such as the Task Scheduler, the only form of quoting that is recognized is "..."
(double-quoting), not also '...'
(single-quoting).[1]
Therefore, replace:
# WRONG: '...' quoting
-NoProfile -ExecutionPolicy Bypass -File 'C:\temp\myScript.ps1'
with:
# OK: "..." quoting
-NoProfile -ExecutionPolicy Bypass -File "C:\temp\myScript.ps1"
Note: Given that your specific file path doesn't contain spaces, you may also pass it unquoted.
The only reason that '...'
quoting worked in the following:
-NoProfile -ExecutionPolicy Bypass -command "& {. 'C:\temp\myScript.ps1' }"
was the use of the -Command
parameter of pwsh.exe
, the PowerShell (Core) 7 CLI, which causes the value of its "..."
-enclosed argument to be interpreted as PowerShell code, where '...'
quoting is recognized.
By contrast, -File
- which does not involve interpretation of its argument as PowerShell code - only accepts an "..."
-enclosed argument as the file path, and, similarly, only recognizes "..."
quoting around any subsequent, pass-through arguments.
For general guidance on when to use -Command
vs. -File
, see this answer.
As an aside:
"& { ... }"
in order to invoke code passed to PowerShell's CLI via the -Command
(-c
) parameter - just use "..."
directly. Older versions of the CLI documentation erroneously suggested that & { ... }
is required, but this has since been corrected.[1] The same applies to calls from cmd.exe
.