powershell如何在if条件下将多个数字传递到数字范围

powershell how to pass multiple number into number range in if condition

我有以下代码,我在 $a 中传递 101,102 号码:

$a = Read-host enter number 
$a -In 100..300

它给了我 'False' 而不是 'True' ,我想在我的脚本中使用这个概念但无法得到真实的结果 参考link:How to tell if a number is within a range in PowerShell

如果您在出现提示时逐字输入 101,102,那么它将被解释为字符串,而不是整数,并且不能自动转换为其他任何内容。字符串 101,102 不是 100300 范围内的整数。

如果在提示时输入101102,将返回True

如果您打算传递以逗号分隔的多个数字,首先您需要将 string 转换为 array,此外,您还需要循环这些值并将它们中的每一个与 -in 运算符进行比较。

下面是一个如何实现的例子:

[regex]::Matches(
    (Read-host "Enter numbers separated by a comma"), '\d+'
).Value.ForEach({$_ -in 100..300})

示例:

Enter numbers separated by a comma: 123,5000,10,200
True
False
False
True

现有答案中有很好的信息,但让我尝试系统地解释一下:

  • Read-Host 仅 returns 类型为 string 单个对象 [string]).

  • 如果您想将该字符串解释为项目列表,您必须自己进行拆分,例如 -splitstring splitting operator

  • 此外,如果您希望字符串(标记)为 数字,则必须 cast到所需的数字类型,例如[int]

  • 最后,-in operator can only test a single LHS object against the RHS array. To test multiple ones you need to test each, which the sample code below does with the .Where() array method:

# Prompt the user for a comma-separated list of numbers, split the result
# string into individual number strings and convert them to integers.
# Note: This will fail with non-numeric tokens.
#       Entering nothing will yield a single-element array containing 0
#       Add error handling as needed.
$numbers = [int[]] ((Read-Host 'Enter list of numbers') -split ',')

# Make sure all numbers provided are in the expected range.
if ($outOfRangeNumbers = $numbers.Where({ $_ -notin 100..300 })) {
  Write-Warning "Numbers that are out of range: $outOfRangeNumbers"
}