Search code examples
powershellpowershell-remoting

User input to perform action


I'm building a script that I want to allow for user input to take action.

Currently this tool can checked all remote servers for any automatic stopped services. I do not want the script to automatically start them though. What I would like user input to start these services.

Write-Host "Checking for Stopped Services..."

$stoppedServices = Invoke-Command $Servers {
    Get-CimInstance Win32_Service -ComputerName $Servers -Filter "startmode = 'auto' AND state != 'running'" |
        Sort state | select name, state
} -Credential $Credential

if ($stoppedServices -ne $null) {
    Clear-host
    $stoppedServices           
} else {
    Clear-Host
    Write-Host ("No stopped services found!")
}

So users have the ability to see the stopped services. I want to do 2 things from this. Write out the stopped services with the option, do you want to start these stopped services?

With that option then either exit or start the service. I'd imagine I can achieve this with another foreach loop but can never get it work.


Solution

  • You may want to use Get-WmiObject instead of Get-CimInstance, collect the matching services in a hashtable, and pass the list into Out-GridView with the -PassThru option. The gridview will return just the objects selected by the user which you can use to call the StartService() method on the service object in the hashtable.

    $svc = @{}
    Get-WmiObject Win32_Service -Computer $Servers -Credential $Credential -Filter "startmode = 'auto' AND state != 'running'" |
        ForEach-Object { $svc[$_.DisplayName] = $_ }
    
    $svc.Values | Select-Object SystemName, DisplayName, State |
        Sort-Object State, SystemName, DisplayName |
        Out-GridView -PassThru |
        ForEach-Object { $svc[$_.DisplayName].StartService() }