15

I'm trying something really simple here, but can't figure out where I'm going wrong. I've found many other useful discussions of this - particularly here - but haven't found anything that covers my specific scenario.

In powershell, I have typed the following:

$path = "c:\program files\"
$path2 = "c:\program files\fred2\"
echoargs $path $path2
echoargs "$path" "$path2"

In both calls to echoargs, I get

Arg 0 is <c:\program files" c:\program>
Arg 1 is <files\fred2">

back as the result. How can I get the parameters to be passed through correctly?

NB: In my real script the path variables are built up from a few config parameters, so I can't just pass them directly in single quotes.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
James Crowley
  • 3,911
  • 5
  • 36
  • 65
  • Please include more of your actual code. When I tried your sample I got `c:\program files\ ` and `c:\program files\fred2\ ` for both. – Andy Arismendi Jan 16 '12 at 17:01
  • @AndyArismendi very strange. I just copied+pasted directly from this question back into the powershell ISE and got exactly as I described? which version of powershell are you using? I'm using 2.0 I believe – James Crowley Jan 16 '12 at 17:13
  • Yea I just defined a function to test: `function echoargs { $args[0]; $args[1] }`. – Andy Arismendi Jan 16 '12 at 17:46
  • Oh sorry I think I misunderstood. If I understand now, echoargs must be another application and you want the other app to receive a single parameter with spaces in it... – Andy Arismendi Jan 16 '12 at 17:56

2 Answers2

22

You need to enclose your result strings in single quotes inside the scope of the execution:

echoargs "'$path'" "'$path2'"

This will pass them to the called application delimited inside single quotes, but since the entire string is still in double quotes your parameter will be expanded correctly.

JNK
  • 63,321
  • 15
  • 122
  • 138
4

In the latest drop of PSCX we've update EchoArgs.exe to also show the entire command line as the receiving app sees it. In this case, you get:

14 >  echoargs $path $path2
Arg 0 is c:\program files" c:\program
Arg 1 is files\fred2"

Command line:
"C:\Users\Keith\Documents\WindowsPowerShell\Modules\Pscx\Apps\EchoArgs.exe"  "c:\program files\" "c:\program files\fred2
\"

It would seem that the \" is causing the trailing double quote to be escaped somewhere. BTW the same happens in CMD.exe from what I can tell. If you modified your paths to remove the trailing slash (or if you used forward slashes), this wouldn't happen.

20 >  $path = "c:\program files"
21 >  $path2 = "c:\program files\fred2"
22 >  echoargs $path $path2
Arg 0 is c:\program files
Arg 1 is c:\program files\fred2

Command line:
"C:\Users\Keith\Documents\WindowsPowerShell\Modules\Pscx\Apps\EchoArgs.exe"  "c:\program files" "c:\program files\fred2"

If you get these paths from somewhere else, you can remove the trailing backslash like so:

$path = $path.TrimEnd("\")
Keith Hill
  • 194,368
  • 42
  • 353
  • 369