Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 422
Hayk Martiros Avatar asked Sep 01 '12 00:09

Hayk Martiros


People also ask

How do I pass multiple command line arguments in PowerShell?

To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.

How do you pass an argument in PowerShell?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

Can you run batch commands in PowerShell?

To run the batch commands from PowerShell, we can use the Start-Process cmdlet as earlier explained and which executes a cmd command on the server.


1 Answers

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

set ARGS=%*
set ARGS=%ARGS:$=`$%
"%POWERSHELL%" -Command "%SCRIPT%" %ARGS%
like image 124
Ansgar Wiechers Avatar answered Sep 29 '22 05:09

Ansgar Wiechers