unknown
unknown

Reputation: 1913

Store the output of command ran on remote system and list in proper format and select the option from that list in powershell?

I am running the below command in one of my powershell function to get the list of services from remote computer

Get-WmiObject -Class Win32_Service -filter "name like '$envlist%'" -Impersonation 3 -Credential abcdomain\PXXXX -ComputerName $server  | Format-List -Property Name

The above command gives me the below output and I want to store it in variable and list it in proper format

Name : ABC_xx02_TT_xcedf_1.0.00.0101

Name : ABC_xx02_TT_nghk_2.1.0.99999

Name : ABC_xx02_TT_nmk_3_1.0.3.7890

Name : ABC_xx02_TT_pnp_4.0.0.123

I am expecting the output in below way:(the below services could be more so need to use something like counter).Once I select any choice from below I want to store it in variable for e.g if I select "3" then it should store in variable $serivcename = ABC_LA02_TT_nmk_3_1.0.3.7890

1. Press 1 to select ABC_xx02_TT_xcedf_1.0.00.0101

2. Press 2 select ABC_xx02_TT_nghk_2.1.0.99999

3. Press 3 to select ABC_xx02_TT_nmk_3_1.0.3.7890

4. Press 4 to select ABC_xx02_TT_pnp_4.0.0.123

Please make a selection:

Upvotes: 1

Views: 48

Answers (2)

Theo
Theo

Reputation: 61168

I have no idea of course what could be in '$envlist%', but apparently that gives you the result you need. Right now, your code uses Format-List, but that does not display a usable console menu.

I would do it like this:

$collection = (Get-WmiObject -Class Win32_Service -Filter "name like '$envlist%'" -Impersonation 3 -Credential abcdomain\PXXXX -ComputerName $server).Name
while ($true) {
    Clear-Host
    for ($i = 1; $i -le $collection.Count; $i++) {
        # build your menu
        "{0}. Press {0} to select {1}" -f $i, $collection[$i - 1]
    }
    $answer = Read-Host "Please make a selection. Press Q to quit"

    # test if the (string) answer is in range, or if the user wants to quit
    # if so, break the while loop
    if ($answer -match "[1-$($collection.Count)Q]") { break }

    # when you reach this point, the user made an invalid choice
    Write-Host "Invalid input, please try again" -ForegroundColor Red
    Start-Sleep -Seconds 3
}

# do whatever you need with the selected option
if ($answer -ne 'Q') {
    Write-Host "User selected '{0}'" -f $collection[[int]$answer - 1]
    # DoStuff $collection[[int]$answer - 1]
}

Upvotes: 1

wasif
wasif

Reputation: 15488

Try this:

$i = 0
Get-WmiObject -Class Win32_Service -filter "name like '$envlist%'" -Impersonation 3 -Credential abcdomain\PXXXX -ComputerName $server  | Foreach {
  $i++
 Write-host "$($i). Press $($i) to select $($_.name.split('=')[1])"
}
$input = read-host "Please make a selection"

Now selection will be stored in $input.

Upvotes: 1

Related Questions