I am writing a PowerShell (version 7) script on my Linux machine where I want to use Linux commands. I encountered a problem when trying to pass parameters using a string variable.
Let's have two strings with parameters:
PS> $param1 = '-la'
PS> $param2 = '-l -a'
Case is the first one works as expected, but the second one shows an error - why?
PS> ls $param1
[EXPECTED OUTPUT HERE]
PS> ls $param2
# wrong option -- ' '
# type „/usr/bin/ls --help” for more info.
When Invoke-Expression is used though, the parameter sets are parsed as expected
PS> Invoke-Expression "ls $param1" #
PS> Invoke-Expression "ls $param2" # both work ok
It looks like PowerShell treats leading dashes in a special way when used for commands and I would like to understand this behaviour, because it's not only why the '-l -a' didn't work but also why '-la' worked.
There is a SO case that touches my problem but not fully - How to pass a string variable to a command in powershell?
-l -aas a SINGLE parameter because it's a string. And there is not parameter calledl -a. Viceversa-ladoes exists\gets correctly interpreted as multiple parameters. I guess if you NEED to pass multiple separated parameters as a single string, you could tryls $param2.Split(' ')$passThruArgs = @('-f', 'bar.json'); foo.exe $passThruArgs(orfoo.exe @passThruArgs) to in effect callfoo.exe -f bar.json. See the linked duplicate for details.