简体   繁体   中英

How can I pass batch arguments with dots into a powershell script?

I have a batch script that will be run by an an external process that is not under my control. The external process can supply a variable amount of arguments to the batch script. I then want to pass these variables to a powershell script. The problem is, is that some of these variables look like:

-Dfoo.bar=baz

Powershell for some reason breaks it up into two args. On the command line, I can just add quotes around the arg and call it a day. But how would I get batch to pass it that way? Here is my script:

@echo off
SET CMD=C:\Scripts\foo.ps1

PowerShell.Exe -Command "%CMD%" %*

I noticed this question is very similar to this one . Here he's escaping the $ character. I tried doing something similar for the dot and/or the dash char, but have no luck. Anyone has any ideas?

If you call your script from CMD, it works just fine as-is:

C:\>.\foo.bat -Dfoo.bar=baz
args are -Dfoo.bar=baz

To fix the issue when you run the batch script from PowerShell use the stop parsing operator --% eg:

C:\ PS> .\foo.bat --% -Dfoo.bar=baz
args are -Dfoo.bar=baz

To pass things as literal you can enclose them in single quotes. My suggestion would be to do that for your arguments, and then break them up once in PowerShell, and splat them to your command.

@echo off
SET CMD=C:\Scripts\foo.ps1

PowerShell.Exe -Command "%CMD%" '%*'

Then in Powershell:

Param($PassedArgs)
$SplitArgs = $PassedArgs.trim("'").split(" ")
SomeCommand @SplitArgs

Something like this might work:

@echo off

set "CMD=C:\Scripts\foo.ps1"
set "ARGS=%*"
set "ARGS=%ARGS: =' '%"

PowerShell.Exe -Command "%CMD%" '%ARGS%'

Demonstration:

C:\>
@echo off

set "CMD=C:\test.ps1"
set "args=%*"
set "args=%args: =' '%"
powershell -Command "%CMD%" '%args%'

C:\>
$args | % { $_ }

C:\>
-Dfoo.bar=baz
-something

Single quotes around an argument prevent PowerShell from doing funky things with that argument. By replacing spaces in the argument list with ' ' you put single quotes after one argument and before the next one. The "outer" single quotes around the variable add the missing quotes before the first and after the last argument.

C:\>
@echo off
set "args=%*"
echo %args%
set "args=%args: =' '%"
echo %args%
echo '%args%'

C:\>
-Dfoo.bar=baz -something
-Dfoo.bar=baz' '-something
'-Dfoo.bar=baz' '-something'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM