Home > Net >  Powershell script to check services - start services - return status that it is started
Powershell script to check services - start services - return status that it is started

Time:10-12

I have a set of services on a machine that I need to validate are running after reboots. I would like to run a powershell script that will do the following

  1. Show current status of services
  2. Show which services are not running
  3. actually Start the services
  4. lastly check and return confirmation that all services are running

This is the code I have so far and I've been testing variations but I'm stuck as when I hit enter, it just returns to a new line and does not start any of the stopped services.

$service = 'Service1','Service2','Service3'

get-service  -name $service -WarningAction SilentlyContinue| Format-Table -Property 
DisplayName,Status -AutoSize

foreach($services in $service){
    if($service.status -ne "running"){
        write-host attempting to start $service
        get-service -name $service | start-service -force
        }
    else{
        write-host all services are running and validated
        }
    }

CodePudding user response:

You are falling into the trap you set for yourself by reversing the multiple ($services) with the singular ($service).

Also, I would first get an array of services from your list in a variable, so it is easier to see if all are running or not

Try:

$services = 'Service1','Service2','Service3'  # an array of multiple services to check

# get an array of services that are not running
$notRunning = @(Get-Service -Name $services | Where-Object { $_.Status -ne 'Running' })
if ($notRunning.Count -eq 0) {
    Write-Host "all services are running and validated"
}
else {
    foreach ($service in $notRunning){
        Write-Host "attempting to start $service"
        Start-Service -Name $service
    }
}

# now show the current status after trying to start some when needed
Get-Service -Name $services | Format-Table -Property DisplayName,Status -AutoSize
  • Related