Reputation: 11130
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?
Upvotes: 1
Views: 1066
Reputation: 13452
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.
Upvotes: 0
Reputation: 11130
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"]
Upvotes: 0
Reputation: 2159
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]
Upvotes: 1