简体   繁体   中英

Powershell: Unquoting arguments when invoking an external command

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?

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]

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"]     

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.

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