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

如何编写PowerShell脚本实现仅运行用户选中的指定命令

PowerShell 选择执行指定命令解决方案

完整可运行代码

# 预定义所有可选命令列表
$commandList = @(
    "Get-Service -Name BITS",
    "Get-Service -Name WinDefend",
    "Get-Service -Name Winmgmt",
    "Get-Service -Name WdNisSvc"
)

# 输出选项提示给用户
Write-Host "请选择你想要运行的命令:`n"
for ($index = 0; $index -lt $commandList.Count; $index++) {
    Write-Host "$($index + 1). $($commandList[$index])"
}

# 接收用户输入,注意不要使用$input作为自定义变量名,$input是PowerShell内置自动变量会冲突
$userChoice = Read-Host -Prompt "`n请输入对应序号选择要执行的操作"

# 校验输入合法性
if ([string]::IsNullOrWhiteSpace($userChoice)) {
    Write-Warning -Message "未选择任何输入"
    exit
}
$choiceNum = 0
if (-not [int]::TryParse($userChoice, [ref]$choiceNum) -or $choiceNum -lt 1 -or $choiceNum -gt $commandList.Count) {
    Write-Warning -Message "输入无效,请输入 1 到 $($commandList.Count) 范围内的有效序号"
    exit
}

# 执行选中的命令
$selectedCommand = $commandList[$choiceNum - 1]
Write-Host "现在将执行 [$selectedCommand]"
Invoke-Expression -Command $selectedCommand

关键说明

  • 禁止使用$input作为自定义变量名:$input是PowerShell内置的自动变量,用于接收管道传入的内容,自定义变量复用该名称会导致不可预期的异常。
  • 新增输入合法性校验逻辑:避免用户输入非数字、超出序号范围的内容导致脚本报错。
  • 命令执行使用Invoke-Expression,适配当前所有命令均为可信预设的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:54:02