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

PowerShell文件完整性监控脚本:输入验证后代码终止求助

PowerShell文件完整性监控脚本循环问题修复

你的脚本执行到do-while循环后停止,是因为代码里有两个关键错误:

1. 顶层使用return直接终止脚本

在PowerShell脚本的顶层作用域中,return会直接结束整个脚本的执行,而非把值返回给循环外部。所以当用户选择A或B时,脚本会立刻停止,不会继续执行后续逻辑。

2. while条件判断逻辑错误

$userinput -notcontains $selections的写法颠倒了操作数:-contains/-notcontains要求左边是数组,右边是单个元素。你现在左边是单个字符串$userinput,右边是数组$selections,这个判断逻辑完全错误,会导致循环条件不符合预期。

修复后的代码

# 初始询问用户操作选项
$initpromptquestion = "What would you like to do?`n`n     A) Collect new baseline.`n`n     B) Begin monitoring files with saved baseline.`n`nSelect 'A' or 'B'"
$errormessage = "Invalid entry. Please select 'A' or 'B'."
$selections = @('A','B')

do {
    $userinput = Read-Host -Prompt $initpromptquestion
    switch($userinput) {
        A { 
            $selectedOption = 'A'
            break
        }
        B { 
            $selectedOption = 'B'
            break
        }
        default { Write-Host $errormessage -ForegroundColor DarkRed -BackgroundColor White } 
    }
} while ($userinput -notin $selections)

# 后续可通过$selectedOption执行对应逻辑
Write-Host "You selected: $selectedOption"

修改说明

  • 把return替换为变量赋值+break,跳出switch后继续执行循环后的代码
  • 将while条件改为$userinput -notin $selections,正确判断输入是否不在可选列表中
  • 新增$selectedOption变量存储用户选择,方便后续脚本逻辑调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:17:09