0

I have a script foo.cmd:

echo %1 %2

In PowerShell I run:

foo.cmd "a,b" "c"

Expected output: a,b c
Actual output: a b

Why?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
igbgotiz
  • 892
  • 1
  • 8
  • 28
  • This is an example of strange behavior introduced by PowerShell (there is another example [here](http://stackoverflow.com/questions/35313953/findstr-always-fails-to-find-hash-string-in-text-file)). In other words: this would work as expected in a pure Batch file. – Aacini Feb 24 '16 at 18:22

1 Answers1

0

The double quotes are removed after PowerShell parsed the command line and passes it to CMD for execution, so CMD actually sees a statement

foo.cmd a,b c

Since the comma is one of CMD's delimiter characters that statement is equivalent to

foo.cmd a b c

To avoid this behavior you need to ensure that the double quotes are preserved when passing the arguments to CMD. There are several ways to achieve this. For instance, you could put the double quoted arguments in single qoutes:

foo.cmd '"a,b"' "c"

and change the positional parameters in the batch script to %~1, %~2 so that CMD removes the double quotes from the arguments.

If you have PowerShell v3 or newer you can use the "magic parameter" --% to avoid the nested quotes:

foo.cmd --% "a,b" "c"

You still need %~1 and %~2 in the batch script, though.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Can you explain the "PowerShell parsed the command line and passes it to CMD for execution" part? What is the exactly underlying mechanism that sees a cmd be spun up and the parsed command passed to it from PowerShell? – igbgotiz Feb 24 '16 at 03:16
  • What is there to explain? PowerShell runs batch scripts with the handler that is configured for batch scripts (usually CMD). And it parses every statement, otherwise it wouldn't be able to expand variables, expressions, etc. – Ansgar Wiechers Feb 24 '16 at 03:21
  • So does PowerShell actually starts a new cmd and the cmd runs "foo.cmd a,b c"? – igbgotiz Feb 24 '16 at 03:29