In powershell, how to build String arrays from “remaining” arguments passed from command line? [duplicate]

こ雲淡風輕ζ 提交于 2020-08-09 14:05:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/63161439/in-powershell-how-to-build-string-arrays-from-remaining-arguments-passed-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!