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

如何在PowerShell脚本中为带ValidateSet的函数参数实现交互式输入?

问题描述

我写了一个带ValidateSet约束的PowerShell函数,用来防止用户输入错误内容。但在脚本里调用这个函数时,没法通过输入提示应用这个约束。我知道可以用Read-Host,但它没法限制输入,容易出错。目前只能让用户先在脚本外运行函数,太不方便了。

函数代码:

function ShowStackOverFlowCommunity-ExampleOfFunction {
    PARAM (
        
        [parameter()]
        [validateset(
            "Don't Input Incorrect Things",
            "Stop it",
            "I Swear to God..."
        )]
        [string]
        $pplbedumb

    )

    write-host "Hi I'm a script. TeeHee"
    write-host $pplbedumb;

}

脚本示例:

$path = read-host "input path to file"
$pathdata = gc $path;

foreach ($item in $pathdata) {
    get-service $item | select name, balls, etc. 
    if ($item.balls) {
        ShowStackOverFlowCommunity-ExampleOfFunction 
    }
}
解决方案

方法1:让参数强制交互式选择

直接给函数的$pplbedumb参数加上Mandatory=$true,PowerShell会自动弹出带可选列表的交互式提示,用户只能选ValidateSet里的选项,不用额外写输入逻辑。

修改后的函数:

function ShowStackOverFlowCommunity-ExampleOfFunction {
    PARAM (
        [parameter(Mandatory=$true)]
        [validateset(
            "Don't Input Incorrect Things",
            "Stop it",
            "I Swear to God..."
        )]
        [string]
        $pplbedumb
    )

    write-host "Hi I'm a script. TeeHee"
    write-host $pplbedumb;
}

现在在脚本里调用ShowStackOverFlowCommunity-ExampleOfFunction时,会自动弹出选择提示,用户只能从指定选项里挑,不会输入错误内容。

方法2:自定义带验证的输入函数

如果不想把参数设为必填,自己写个小函数处理输入,强制用户从指定选项中选择:

function Get-ValidatedInput {
    param(
        [Parameter(Mandatory=$true)]
        [string[]]$ValidOptions,
        [string]$Prompt = "请选择一个选项:"
    )

    do {
        Write-Host $Prompt
        # 列出所有选项带序号
        for ($i=0; $i -lt $ValidOptions.Count; $i++) {
            Write-Host "[$($i+1)] $($ValidOptions[$i])"
        }
        $userInput = Read-Host "输入序号或选项内容"
        
        # 检查是否是有效序号
        if ($userInput -match '^\d+$' -and [int]$userInput -ge 1 -and [int]$userInput -le $ValidOptions.Count) {
            return $ValidOptions[[int]$userInput - 1]
        }
        # 检查是否是有效选项内容
        if ($ValidOptions -contains $userInput) {
            return $userInput
        }
        Write-Host "输入无效,请重新选择!" -ForegroundColor Red
    } while ($true)
}

然后在脚本里调用时,用这个函数获取合法输入再传给目标函数:

$path = read-host "input path to file"
$pathdata = gc $path;

foreach ($item in $pathdata) {
    get-service $item | select name, balls, etc. 
    if ($item.balls) {
        $selected = Get-ValidatedInput -ValidOptions @("Don't Input Incorrect Things", "Stop it", "I Swear to God...") -Prompt "请选择操作选项"
        ShowStackOverFlowCommunity-ExampleOfFunction -pplbedumb $selected
    }
}

用户输入时可以选序号或者直接输选项内容,不符合要求的会被提示重新输入,保证输入符合约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:15:33