简体   繁体   中英

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

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
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM