Home > Blockchain >  Run only selected command / line
Run only selected command / line

Time:11-15

let's say that I have following Powershell script that contains severall powerhsell commands

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

How can I make my script like that that it would ask which of 4 commands it would run like

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

and they based of my selection it will run only wanted command

EDIT: I was now able to solve problem this far but now issue is that: how do I prompt these to user so user can select them and save the answer so I can use it after "Write-Host "Now we can perform [$input]""

 $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"
     }

CodePudding user response:

You can create a menu like below.

If you're interested in learning what's being applied on the menu:

$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')
  • Related