You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell的Do Until循环实现带确认重选的交互式集群菜单

改写PowerShell集群选择脚本(支持重新选择)

完全可以通过Do Until循环实现选择确认与重新选择的功能,以下是修改后的脚本:

write-host ""
Write-host -ForegroundColor yellow "Choose which Cluster you want to gather ratios on:"
write-host "(it may take a few seconds to build the list)"
write-host ""

$ICLUSTER = get-cluster -server $VIServer | Select-Object Name | Sort-object Name
if ($null -eq $ICLUSTER)
{
    Update-log "Unable to find Cluster Information.Please verify the cluster status before proceed `n"
    break 
}
else
{
    # 初始化确认标记
    $confirm = 'N'
    # 循环直到用户确认选择正确
    Do {
        # 重新显示集群菜单
        $i = 1
        $ICLUSTER | ForEach-Object {Write-Host $i":" $_.Name; $i++}
        
        # 验证输入的有效性,确保是数字且在有效范围内
        do {
            $HCLUSTER = Read-host "Choose the name of cluster you want to select on by entering corresponding number:"
            # 检查输入是否为数字,且索引存在
            $isValid = [int]::TryParse($HCLUSTER, [ref]$null) -and ($HCLUSTER -ge 1 -and $HCLUSTER -le $ICLUSTER.Count)
            if (-not $isValid) {
                Write-Host "Invalid input! Please enter a number between 1 and $($ICLUSTER.Count)" -ForegroundColor Red
            }
        } until ($isValid)

        $SCLUSTER = $ICLUSTER[$HCLUSTER -1].Name
        Write-Host "You have selected $($SCLUSTER)." -ForegroundColor Cyan
        $confirm = Read-Host "Is this correct? (Y/N)"
        write-host ""
    } Until ($confirm -eq 'Y' -or $confirm -eq 'y')

    Update-log "You have confirmed selection of $($SCLUSTER). `n"
    start-sleep -s 3
}

关键改动说明:

  • 外层用Do Until循环包裹选择流程,直到用户输入Y/y确认选择
  • 新增输入验证逻辑:确保用户输入的是有效数字,且对应集群列表的索引范围,避免因无效输入导致的脚本错误
  • 每次循环都会重新显示集群菜单,方便用户重新选择
  • 确认环节明确告知用户当前选择,并等待确认指令

内容的提问来源于stack exchange,提问作者Sajith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:15:56