Powershell script to checking services on multiple remote machines and to start them if they are not running

Viewed 31

New to Powershell, My goal is to go through a list of remote Computers and check to see if certain services are running on them and starting the services if they are not. what would be the best approach in creating a variable for the services on said servers?

Server1.txt - 'ServiceA ServiceB ServiceC'
Server2.txt - 'ServiceD ServiceE ServiceF'
Server3.txt - 'ServiceG ServiceH'

$services = get-content .\Server1.txt

       

$services | ForEach {
    try {
        Write-Host "Attempting to start '$($.DisplayName)'"
        Start-Service -Name $.Name -ErrorAction STOP
        Write-Host "SUCCESS: '$($.DisplayName)' has been started"
    } catch {
        Write-output "FAILED to start $($.DisplayName)"
    }
}

Thank you.

1 Answers

In your input, you have mentioned one text file for each server which is not advisable. Also there is no computer name in your Start-service Command. Please find my input sample below.

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

And here is the powershell script, since you have mentioned different services for each server there is a need for using 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"
        }
     
    }
}

I haven't tested the script for starting the service, but the loop works properly for multiple servers and their respective services. Thanks!

Related