在powershell中,如何从“剩余"构建字符串数组.从命令行传递参数? [英] In powershell, how to build String arrays from "remaining" arguments passed from command line?
问题描述
当函数需要String数组时,在命令行上键入("arg0","arg1","arg2")是不方便的.像本例一样:
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
}
... -ScriptName之后的所有参数都必须使用显式数组语法.如何避免这种情况,以便我可以输入
... 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
还有$ ArgList值传递给可执行文件吗?
And still have an $ArgList value to pass to the executable?
推荐答案
注意:
-
该解决方案由此答案提供,其中显示了如何使用
ValueFromRemainingArguments
parameter属性,以在单个数组参数中收集所有单独的未绑定位置参数.
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.
我认为您的功能已简化;如所写,在链接的答案中实现解决方案实质上使该功能变得不必要-您可以简单地调用 foo.gradle arg0 arg1 arg2
直接(假设 foo.gradle
是直接可执行的,这就是您的函数所建议的).
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).
顺便说一句:使用 $ ScriptName
而不是"$ ScriptName"
就足够了,因为-与POSIX类似的外壳不同-PowerShell使您能够使用变量 unquoted ,即使它们的值包含空格或其他shell元字符(不执行所谓的shell扩展).
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).
至:
当函数需要String数组时,在命令行上键入("arg0&","arg1","arg2")是不方便的.
It is inconvenient to type ("arg0", "arg1", "arg2") on the command line when a function needs a String array.
繁琐的语法("arg0&","arg1","arg2")
仅在 expression 解析模式下需要.
The cumbersome syntax ("arg0", "arg1", "arg2")
is only needed in expression parsing mode.
在参数解析模式下-当您将参数传递给命令时-可以使用传递数组语法-不带括号且不带引号(除非元素是包含空格或PowerShell元字符的 literal ,例如'arg 0'
):
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
有关PowerShell的两种基本解析模式的更多信息,请参见此答案.
For more information about PowerShell's two fundamental parsing modes, see this answer.
这篇关于在powershell中,如何从“剩余"构建字符串数组.从命令行传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!