首页 > 解决方案 > 仅运行选定的命令/行

问题描述

假设我有以下包含几个 powerhsell 命令的 Powershell 脚本

Get-Service -Name  BITS
Get-Service -Name WinDefend
Get-Service -name Winmgmt
Get-Service -Name WdNisSvc

我怎样才能让我的脚本像这样询问它会运行 4 个命令中的哪一个

Select which command you would like to run:

1. Get-Service -Name  BITS
2. Get-Service -Name WinDefend
3. Get-Service -name Winmgmt
4. Get-Service -Name WdNisSvc

他们根据我的选择将只运行想要的命令

编辑:到目前为止,我现在能够解决问题,但现在的问题是:如何向用户提示这些,以便用户可以选择它们并保存答案,以便我可以在“Write-Host”之后使用它现在我们可以执行 [$输入]””

 $input = Read-Host -Prompt 'Select what operation you want to perform'
 
 1. Get-Service -Name  BITS
 2. Get-Service -Name WinDefend
 3. Get-Service -name Winmgmt
 4. Get-Service -Name WdNisSvc
 
     if ($input) {
      Write-Host "Now we can perform [$input]"
        **here should then answer be executed**
     } else {
         Write-Warning -Message "No input selected"
     }

标签: powershell

解决方案


您可以创建如下所示的菜单。

如果您有兴趣了解菜单上的应用:

$services = @(
    'BITS'
    'WinDefend'
    'Winmgmt'
    'WdNisSvc'
)

$servCount = $services.Count

do
{
    # Phrase this correctly so it's clear user should select a Number
    'Select a Service you would like to query:'
    
    $services | ForEach-Object -Begin { $i = 1 } -Process {
        "$i. $_"; $i++
    }

    switch -Regex($selection = Read-Host)
    {
        "^[1-$servCount]{1}$" {
            Get-Service $services[$selection-1]
            'Press ENTER to continue...'
            Read-Host
            Clear-Host
            break
        }
        "Q" { break }
        Default { Write-Warning 'Invalid Selection!' }
    }
}
until($selection -eq 'Q')

推荐阅读