Powershell - 用户输入的数组范围
获取数组范围的用户输入的最简单方法是什么。
例如:
function MyArrayOfMachines {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)][string]$Machine
# What should I assign the $Range variable as?
)
# Hardcoded range. User should be able to enter the range
$Range = 2..5
for ($i=0; $i -lt $array.length; $i +=1)
{
$result = $array[$i]
$output = $machine+$result
$output
}
}
上面的函数应该将输入作为机器的名称和数组范围。现在我已经对数组范围进行了硬编码。当我在用户提示中将 $Range 指定为 [Array]$Range 时,会提示 $Range[0] 等。但我希望用户输入范围。
What would be the easiest way to get user input for an array range.
For example:
function MyArrayOfMachines {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)][string]$Machine
# What should I assign the $Range variable as?
)
# Hardcoded range. User should be able to enter the range
$Range = 2..5
for ($i=0; $i -lt $array.length; $i +=1)
{
$result = $array[$i]
$output = $machine+$result
$output
}
}
The above function should take the input as the name of the machine and the array range. For now I have the array range hardcoded. When I assign $Range as [Array]$Range in the user prompt, there is a prompt for $Range[0] etc etc. But I would like the user the enter the range.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这行不通吗?除非我误解了你的问题...
Doesn't this work? Unless I misunderstood your question...
您还可以接受范围作为字符串并自己解析它:
if / else 的原因是用户传递实际范围(如 manojlds 答案),而不是要解析的字符串(如 1..5 )。这意味着您不能强键入参数。
You can also accept the range as a string and parse it yourself:
The reason for the if / else is for cases where the user passes an actual range, as in manojlds answer, rather than a string to be parsed (like 1..5). This means you can't strongly type the param though.
使其成为两个参数:
如果它们输入范围的开始和结束,您可以使用它在函数中动态创建它。
编辑:
要获取字符串的范围,请尝试:
Make it two parameters:
If they input the start and end of the range you can use that to create it dynamically in the function.
EDIT:
To get the range from a string, try:
我同意@manojlds,范围应该作为数组传入。解析字符串限制了用户输入内容的可能性。通过使用
[int[]]
,您可以强制用户指定整数数组。这还允许用户指定一个断开的范围,例如((2..4)+(6..12))
,这在解析字符串时更难允许。在您的示例中,我不确定
$array
来自何处,并且您只需要一行即可返回计算机器名称。您可以创建单个计算机名称、
一系列计算机
或不连续的计算机阵列
I agree with @manojlds, the range should be passed in as an array. Parsing a string limits the possibilities of what a user could enter. By using
[int[]]
you can force the user to specify an array of integers. This would also allow a user to specify a broken range such as((2..4)+(6..12))
which is harder to allow for when parsing strings.In your example I'm not sure where
$array
is coming from, and you only need one line to return a computed machine name.You could create a single machine name,
a range of machines,
or a non-consecutive array of machines
您可以只传递一个字符串并对其进行评估:
进行一些最小的验证以确保用户无法传递任意代码。
You could just pass a string and evaluate it:
Some minimal validation is done to ensure that the user cannot pass arbitrary code.