我在为脚本生成动态选项列表时遇到一些问题。我可以看到它返回选项列表,我可以选择它们中的每一个。但是我的验证并没有像我预期的那样有效。
Write-Host "Gathering cluster information..." -foreground Green
$allclusters = Get-Cluster | Sort Name
$allHosts = $allclusters | Get-VMHost
Write-Host "Found " $allclusters.count " containing " $allHosts.count " Hosts." -Foreground Green
# LoopMain Start
Do {
$userMenuChoice = "y"
Write-Host "Select Cluster to patch:" -Foreground Yellow
for($i=0;$i -le $allclusters.length-1;$i++)
{"[{0}] - {1}" -f $i,$allclusters[$i]}
# Select VMCluster
Write-Host ""
Write-Host "Which Cluster would you like to use (0 to"($allclusters.length-1)")" -ForegroundColor Cyan -NoNewLine ; $clusterSelect = Read-Host " "
Write-Host ""
# Validate selection
IF ($clusterSelect -le ($allclusters.length-1))
{
Write-Host "Selection is valid"
# Display item from clusterarray
Write-Host ""
Write-Host "You selected " -NoNewLine ; Write-Host $allclusters[$clusterSelect] -ForegroundColor Cyan -NoNewLine ; $clusterSelectCont = Read-Host ". Shall we continue? (Y/N)"
}
ELSE
{
Write-Host "Selection is not valid"
$clusterSelectCont = "n"
}
选项列表适用于某些数字,但不是全部。例如,我可以从列表中选择数字12,一切都很好但是数字7失败。我创建选项列表的方式是否存在根本性的错误,或者可能是失败的验证?
答案 0 :(得分:0)
啊,在这里与同事讨论过,建议是使用以下行将变量转换为整数:
[int]$clusterSelect = $clusterSelect
现在按预期验证,我可以毫无问题地选择所有值。