1

It is inconvenient to type ("arg0", "arg1", "arg2") on the command line when a function needs a String array. Like in this example:

function Exec-GradleScript(
    [Parameter(Mandatory)]String] $ScriptName
    [Parameter(Mandatory)][String[]] $ArgList
    ){
    & "$ScriptName" $ArgList
}

... all the arguments after -ScriptName need to be in the explicit array syntax. How can I avoid this, so that I can type

Exec-GradleScript foo.gradle arg0 arg1 arg2

And still have an $ArgList value to pass to the executable?

Charlweed
  • 1,517
  • 2
  • 14
  • 22

1 Answers1

0

Note:

  • The solution is provided by this answer, which shows how to use the ValueFromRemainingArguments parameter property to collect all individual unbound positional arguments in a single array parameter.

  • I presume your function is simplified; as written, implementing the solution in the linked answer essentially makes the function unnecessary - you can simply call
    foo.gradle arg0 arg1 arg2 directly (assuming foo.gradle is directly executable, which is what your function suggests).

  • As an aside: It's sufficient to use $ScriptName rather than "$ScriptName", because - unlike POSIX-like shells - PowerShell allows you to use variables unquoted, even if their value contains spaces or other shell metacharacters (no so-called shell expansions are performed).


As for:

It is inconvenient to type ("arg0", "arg1", "arg2") on the command line when a function needs a String array.

The cumbersome syntax ("arg0", "arg1", "arg2") is only needed in expression parsing mode.

In argument parsing mode - when you pass arguments to a command - arrays can be passed using much looser syntax - without parentheses and without quoting (unless the elements are literals that contain whitespace or PowerShell metacharacters, e.g., 'arg 0'):

# No parentheses around the array, elements unquoted.
Exec-GradleScript foo.gradle  arg0, arg1, arg2

For more information about PowerShell's two fundamental parsing modes, see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775