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

Question:

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?

Answer:

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

Source:

Escaping arguments when passing %* from batch script as $args to powershell script by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply