Reputation: 549
I want to invoke an elevated Powershell to execute a script and pass a bunch of parameters. I would like to have every parameter in the .bat file on its own line. Usually I can use the carat ^ to span commands over several lines in .bat files, just like using a grave accent ` in Powershell scripts. But both don't work in this situation:
As a one-liner it works:
Powershell.exe -Command "& {Start-Process Powershell.exe -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -File %~dp0HelloWorld.ps1 -parameter1 Long -parameter2 list -parameter3 of -parameter4 parameters' }"
Trying to split it up into multiple lines using a caret ^ doesn't work:
Powershell.exe -Command "& {Start-Process Powershell.exe -Verb RunAs -ArgumentList '-ExecutionPolicy Bypass -File %~dp0HelloWorld.ps1 ^
-parameter1 Long ^
-parameter2 list ^
-parameter3 of ^
-parameter4 parameters ^
'}"
Here is an example HelloWorld.ps1
to test with, (has to be in the same directory as the batch file):
param (
$parameter1="",
$parameter2="",
$parameter3="",
$parameter4=""
)
write-host "$parameter1 $parameter2 $parameter3 $parameter4"
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Upvotes: 0
Views: 546
Reputation: 38604
The simplest way to handle the issue in your example case above, is to use doublequotes, "
instead of single, '
. However to prevent cmd.exe
from failing to parse the command, you'll need to escape those nested doublequotes, using backslashes, i.e. \"
.
Example:
@Powershell.exe -Command "& {Start-Process Powershell.exe -Verb RunAs -ArgumentList \" ^
-ExecutionPolicy RemoteSigned ^
-File `\"%~dp0HelloWorld.ps1`\" ^
-parameter1 Long ^
-parameter2 list ^
-parameter3 of ^
-parameter4 parameters ^
\"}"
I have specifically changed the ExecutionPolicy
from Bypass
, (which I wouldn't ever recommend using, even moreso when running elevated), to RemoteSigned
, please do not change it back. Also for added safety, I have quoted your .ps1
file path, which could contain spaces. The backslashes escape the doublequotes for the cmd.exe
parser, (as already mentioned), and then backticks escape the remaining nested doublequotes for the powershell.exe
parser.
Upvotes: 3