H.v.M.
H.v.M.

Reputation: 1633

Use .bat to run another .bat with Powershell, with spaces in arguments

I'm trying to get a batch file to use Powershell to run another batch file. The first batch is to be run with cmd (i.e. by clicking on it).

a.bat

POWERSHELL Start-Process -FilePath b.bat -ArgumentList 'a b','c d' -verb runas >nul 2>&1

b.bat

ECHO %1
ECHO %2
ECHO %3
ECHO %4
ECHO %*
SET /P=Press enter to exit...

I've tried various argument lists, but I can't pass an argument with spaces. Here is what I've observed based on what I've tried. Hopefully at least some of these are wrong.

Here are some of my attempts at argument lists which inform the above:

How can I pass an argument list with arguments that have spaces?

Context: my aim is to run a .bat which calls another .bat with arguments, which then uses Powershell to call itself with admin privileges while retaining the arguments. I've gotten it to work except when the arguments have spaces.

Upvotes: 1

Views: 80

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Pass the string value with double-quotes, then use ~ to strip the argument of quotes in the batch script:

ECHO %~1
ECHO %~2
ECHO %*
SET /P=Press enter to exit...

Then:

Start-Process .\b.bat -ArgumentList '"a b"', '"c d"'

Alternatively, invoke the script directly and let PowerShell take care of quoting the arguments:

# use splatting, let PowerShell handle argument quoting
$batchArgs = @('a b', 'c d')
& .\b.bat @batchArgs

Upvotes: 2

Related Questions