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?
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.
% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.
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.
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.
Escape $ characters before you pass %* to the PowerShell script.
set ARGS=%*
set ARGS=%ARGS:$=`$%
"%POWERSHELL%" -Command "%SCRIPT%" %ARGS%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With