0

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?

3
  • 2
    Try : $param2 = @('-l', '-a') Commented Jun 25, 2024 at 9:47
  • 2
    Powershell takes -l -a as a SINGLE parameter because it's a string. And there is not parameter called l -a. Viceversa -la does exists\gets correctly interpreted as multiple parameters. I guess if you NEED to pass multiple separated parameters as a single string, you could try ls $param2.Split(' ') Commented Jun 25, 2024 at 10:15
  • 1
    In short: To build a list of arguments to pass to an external program, do not put them into a single string; instead, create an array with the individual arguments as elements (including option names and values in separate elements, if they would be space-separated in direct use); e.g. $passThruArgs = @('-f', 'bar.json'); foo.exe $passThruArgs (or foo.exe @passThruArgs) to in effect call foo.exe -f bar.json. See the linked duplicate for details. Commented Jun 25, 2024 at 11:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.