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

PowerShell中支持超254字符的choice命令替代方案问询

替代PowerShell choice命令的长提示解决方案

原生choice.exe的/M参数提示文本存在254字符限制,要实现同样的「仅允许输入指定字符」功能且支持超长提示,可以用纯PowerShell自定义函数来实现,以下是具体方案:

自定义实现函数

这个函数完全模拟choice.exe的核心行为,同时支持任意长度的提示文本:

function Select-CharChoice {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Choices,
        [Parameter(Mandatory=$true)]
        [string]$Message
    )

    Write-Host "$Message [$Choices]" -NoNewline

    do {
        $inputKey = [Console]::ReadKey($true).KeyChar.ToString().ToUpper()
        if ($Choices.ToUpper().Contains($inputKey)) {
            $global:LASTEXITCODE = $Choices.ToUpper().IndexOf($inputKey) + 1
            Write-Host $inputKey
            return $inputKey
        }
    } while ($true)
}

使用示例

和你提供的choice.exe示例逻辑完全一致,且支持超长提示:

# 这里可以输入任意长度的提示文本,不受254字符限制
Select-CharChoice -Choices 'YN' -Message "这是一段超长的提示内容,你可以在这里详细描述需要用户确认的操作细节,比如当前脚本将要执行的步骤、潜在的影响等等,无论文字多长都能正常显示,请选择Y确认或N取消?"

if ($LASTEXITCODE -eq 2) {
    Write-Output "你选择了N"
}
elseif ($LASTEXITCODE -eq 1) {
    Write-Output "你选择了Y"
}

功能说明

  • 仅允许输入-Choices参数指定的字符(大小写不敏感)
  • 提示文本支持任意长度,无254字符限制
  • 设置$LASTEXITCODE变量,和choice.exe的返回逻辑一致(第一个选项对应1,第二个对应2,以此类推)
  • 输入时不会显示无效字符,仅在输入有效选项时回显用户选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:27:13