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

PowerShell Do-Until循环异常终止:需持续运行至输入非1-9

解决PowerShell Do-Until循环仅运行一次的问题

问题根源

你的循环终止条件until ($selection -ne 1..9)存在逻辑错误:
在PowerShell中,当用-ne比较单个字符串(Read-Host返回字符串类型)和数组1..9时,会返回一个布尔值数组(每个元素分别比较的结果)。只要这个数组里存在$true,Do-Until就会判定条件满足并终止循环。比如输入1时,$selection -ne 1..9会生成8个$true和1个$false,整体被视为$true,导致循环仅运行一次就终止。

修正方案

使用-notin操作符直接检查输入是否不在目标选项集合中,同时注意集合元素类型要和$selection匹配(都是字符串):

完整修正代码

do
{
    Show-Menu
    $selection = Read-Host "Please choose an option"
    switch ($selection)
    {
        '1' { Get-ChildItem }
        '2' { Get-Host | Select-Object }
        '3' { Get-NetIPConfiguration -Detailed }
        '4' { Get-NetRoute }
        '5' { Get-DnsClientCache }
        '6' { Get-Date -UFormat "%A %B/%d/%Y %T %Z" }
        '7' { Get-ItemProperty -Path HKLM:\ }
        '8' { 
            Stop-Service -Name Spooler -Force
            Restart-Service -Name Spooler -Force
        }
        '9' { Get-Service | Where-Object {$_.Status -eq "Running"} }
    }
    pause
}
until ($selection -notin ('1'..'9'))

关于之前的while无限循环问题

如果之前的while循环条件写成while ($selection -eq 1..9),同样会因为数组比较逻辑错误,导致条件始终被判定为$true(因为比较结果数组里存在$true),进而触发无限循环。若要改用while循环,需先初始化$selection为合法值,再用正确的条件:

$selection = '1'
while ($selection -in ('1'..'9'))
{
    Show-Menu
    $selection = Read-Host "Please choose an option"
    # 后续switch逻辑同前
    pause
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:31:10