2

I had some issues passing an array of strings to a command in PowerShell, so I'm debugging my script. I'm using the EchoArgs.exe program found in the PowerShell Community Extension Project (PSCX). If I execute this script:

Import-Module Pscx
cls

$thisOne = 'this_one\';
$secondOne = 'second one\';
$lastOne = 'last_one'

$args = $thisOne `
    , "the $secondOne" `
    , "the_$lastOne"


EchoArgs $args

I get this result:

Arg 0 is <this_one\>
Arg 1 is <the second one" the_last_one>

Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe"  this_one\ "the second one\" the_last_one

It seems that if a string contains spaces, the last backslash escapes the double quote. In fact all seems working if I escape only that backslash:

Import-Module Pscx
cls

$thisOne = 'this_one\';
$secondOne = 'second one\\';
$lastOne = 'last_one'

$args = $thisOne `
    , "the $secondOne" `
    , "the_$lastOne"


EchoArgs $args

with this result:

Arg 0 is <this_one\>
Arg 1 is <the second one\>
Arg 2 is <the_last_one>

Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe"  this_one\ "the second one\\" the_last_one

Is there a "smart" way in PowerShell (i.e. a cmdlet) to escape any string in order to avoid such issues?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lucazav
  • 858
  • 9
  • 24

1 Answers1

1

Try using Start-Process instead. It has an $Arguments parameter that would suit this better.

See here: PowerShell - Start-Process and Cmdline Switches

Community
  • 1
  • 1
Scott Newman
  • 131
  • 1
  • 1
  • 8