1

Consider the following cmd.exe batch script:

testpar.cmd
@echo [%1] [%2]

If we call it it in Powershell, these results are rather obvious:

PS> .\testpar.cmd arg1 arg2
[arg1] [arg2]          
PS> .\testpar.cmd "arg1 arg2" 
["arg1 arg2"] []     

But, when passing a variable:

PS> $alist= "arg1 arg2"      
PS> .\testpar.cmd $alist     
["arg1 arg2"] []             

It seems that $alist is passed with quotes. One solution:

PS> $alist= "`"arg1`" `"arg2`""  
PS> .\testpar.cmd $alist                                   
["arg1"] ["arg2"]                                          

which identifies arguments, but without stripping quotes.
Another possibility:

PS> Invoke-Expression  (".\testpar.cmd " + $alist)         
[arg1] [arg2]                                              

This works, but is very convoluted. Any better way?
In particular is there a way to unquote a string variable?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
antonio
  • 10,629
  • 13
  • 68
  • 136
  • You don't need to do anything. Just run the shell script as needed: `testpar.cmd arg1 "arg 2"`. PowerShell will automatically quote if needed. Why the question about unquoting a string variable? – Bill_Stewart Apr 04 '15 at 16:43
  • @Bill_Stewart: because there is something similar in the old cmd shell: ` %~` . See `for /?` for more. – antonio Apr 04 '15 at 17:06
  • You could do it (remove quotes from the ends of a string), but what is the purpose of doing so? PowerShell does a pretty good job of quoting automatically where needed. – Bill_Stewart Apr 04 '15 at 18:12

3 Answers3

1

I found a similar question here

What you can do is use a comma: $alist = "a,b"
The comma will be seen as a paramater seperator:

PS D:\temp> $arglist = "a,b"
PS D:\temp> .\testpar.cmd $arglist
[a] [b]

You can also use an array to pass the arguments:

PS D:\temp> $arglist = @("a", "c")
PS D:\temp> .\testpar.cmd $arglist
[a] [c]
Deruijter
  • 2,077
  • 16
  • 27
0

The most convenient way to me to pass $alist is:

PS> .\testpar.cmd $alist.Split()
[arg1] [arg2] 

In this way I don't need to change the way I build $alist.
Besides Split() works well also for quoted long arguments:

PS> $alist= @"
>> "long arg1" "long arg2" 
>> "@

This is:

PS> echo $alist           
"long arg1" "long arg2"   

and gives:

PS> .\testpar.cmd $alist.Split()     
["long arg1"] ["long arg2"]     
antonio
  • 10,629
  • 13
  • 68
  • 136
0

In general, I would recommend using an array to build up a list of arguments, instead of mashing them all together into a single string:

$alist = @('long arg1', 'long arg2')
.\testpar.cmd $alist

If you need to pass more complicated arguments, you may find this answer useful.

Community
  • 1
  • 1
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75