Hayk Martiros
Hayk Martiros

Reputation: 2186

Escaping arguments when passing %* from batch script as $args to powershell script

I have a batch script that takes any number of arguments (list of files) and executes a powershell script with the following command structure:

"%POWERSHELL%" -Command "%SCRIPT%" %*

%POWERSHELL% is the path to PowerShell.exe, and %SCRIPT% is my powershell script that interprets that receives %* as $args. The problem is that if I pass in something like the filename test$file.name, PowerShell receives test.name, presumably because $file is interpreted as an empty variable.

Is there a good way to escape each argument with single quotes or backticks from the batch script, or otherwise deal with this?

Upvotes: 5

Views: 2867

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

Escape $ characters before you pass %* to the PowerShell script.

set ARGS=%*
set ARGS=%ARGS:$=`$%
"%POWERSHELL%" -Command "%SCRIPT%" %ARGS%

Upvotes: 5

Related Questions