tec*_*029 3 variables powershell scripting range
我试图使一个变量等于一个范围。我的脚本包括用户输入,并且该输入必须落在某个范围内。我将在脚本中多次使用该范围,因此我希望它是一个变量。这是我尝试过的:
$serverrange = "1..18"
Run Code Online (Sandbox Code Playgroud)
我试过了
$serverrange = 1..18
Run Code Online (Sandbox Code Playgroud)
我已经用谷歌搜索过,但找不到太多关于此的信息。问题是 PowerShell 并不将其视为一个范围,而是将其视为字面上的 1..18。因此,如果我执行 Write-Output $serverrange,它会显示为“1..18”。所以我的问题是如何让它将其视为一个范围,或者如何更改脚本以合并该范围?这是脚本的其余部分:
#user input for how many servers will be tested
$numofservers = Read-Host -Prompt "How many servers are being tested?"
if($numofservers -eq $serverrange) {
"Proceed"
}
else {
"Server limit exceeded"
}
Run Code Online (Sandbox Code Playgroud)
编辑:没有意识到 $serverrange = 1..18 有效。
正如您后来意识到的,一个不带引号的表达式(例如)1..18
工作得非常好:它使用PowerShell 的范围运算符( ..
)创建一个从1
到 的连续整数数组18
;即,它相当于以下数组文字:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
Run Code Online (Sandbox Code Playgroud)
相比之下,"1..18"
是一个(可扩展)字符串,其内容按原样打印(在本例中为文字1..18
,因为该字符串既不包含变量引用也不包含子表达式)。
重要提示:虽然从技术上讲,它可以用来将字符串Invoke-Expression
评估为 PowerShell语句(例如,),但应避免这种方法:很少是正确的工具,并且会带来安全风险,特别是对于未经消毒的用户输入 - 请参阅PowerShell 团队博客帖子标题为“调用表达式被认为有害”。Invoke-Expression "1..18"
Invoke-Expression
您的挑战似乎是根据用户输入创建这样一个范围,默认情况下是一个字符串,由Read-Host
.
范围运算符能够动态地将任一操作数(范围端点)转换为整数,并愉快地接受表达式作为范围端点:
1..(Read-Host 'Enter the upper bound')
Run Code Online (Sandbox Code Playgroud)
如果您输入3
(如上所述,它作为string返回),PowerShell 会动态将该字符串转换为其等效的整数并创建 array 1..3
,其默认输出如下所示:
1
2
3
Run Code Online (Sandbox Code Playgroud)
也就是说,为了(a) 提供用户友好的提示 (b) 强制执行预定义的输入范围(数字),需要做更多的工作。
所以:
确保用户输入的内容可以转换为 (a) (b) 落在预期范围内的数字;如果没有,再次提示。
收到有效输入后,..
根据需要使用 PowerShell 的范围运算符 ( ) 构造索引数组。
# Define the implied lower bound and the maximum upper bound.
$lowerBound = 1
$maxUpperBound = 18
# Prompt the user for the upper bound of the range, with validation,
# until a valid value is entered.
do {
$userInput = Read-Host -Prompt "How many servers are being tested?"
if (
($upperBound = $userInput -as [int]) -and
($upperBound -ge $lowerBound -and $upperBound -le $maxUpperBound)
) {
break # valid value entered, exit loop.
} else {
# Invalid input: Warn, and prompt again.
Write-Warning "'$userInput' is either not a number or is outside the expected range of [$lowerBound,$maxUpperBound]."
}
} while ($true)
# Create the array of indices based on user input.
1..$upperBound
Run Code Online (Sandbox Code Playgroud)