Confirming before proceeding through checking of services on multiple machines

Viewed 20

My goal is to check the services on multiple remote machines to make sure they are running, and starting them if they are not. I would like to modify the below code to add the ability to ask the user before proceeding to the next $computerName, to display and confirm the status of group of $serviceNames that is being passed through the function.

In a text file servers.txt the contents are as follows:

server1-serviceA,ServiceB,ServiceC
server2-serviceD,ServiceE,ServiceF
server3-serviceG,ServiceH,ServiceI

And here is the powershell script, checking different services for each server using the split function

$textFile = Get-Content C:\temp\servers.txt

foreach ($line in $textFile) {

    $computerName = $line.split("-")[0]  #Getting computername by using Split
    $serviceNames = $line.split("-")[1]  #Getting Service names by using split

    foreach ($serviceName in $serviceNames.split(",")) {
        # Again using split to handle multiple service names

        try {
            Write-Host " Trying to start $serviceName in $computerName"
            Get-Service -ComputerName $computerName -Name $serviceName | Start-Service -ErrorAction Stop
            Write-Host "SUCCESS: $serviceName has been started"
        }
        catch {
            Write-Host "Failed to start $serviceName in $computerName"
        }
     
    }
}
1 Answers

You could use the PSHostUserInterface.PromptForChoice method for this, here is an example of how you can implement it:

# Clear this variable before in case it's already populated
$choice = $null

foreach ($line in $textFile) {
    $computerName = $line.split("-")[0]
    $serviceNames = $line.split("-")[1]

    # If previous choice was not equal to 2 (Yes to All), ask again
    if($choice -ne 2) {
        $choice = $host.UI.PromptForChoice(
            "my title here",                   # -> Title
            "Continue with: ${computerName}?", # -> Message
            @("&Yes", "&No", "Yes to &All"),   # -> Choices
            0                                  # -> Default Choice (Yes)
        )
    }
    # If choice was 1 (No), stop the script here
    if($choice -eq 1) { return }

    # Same logic here
}
Related