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
- Show current status of services
- Show which services are not running
- actually Start the services
- 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