Check Windows Service Status with PowerShell

I needed a way to watch a service and if it was stopped to start it. I created this PowerShell script to check it, start it and create a log, using it in a scheduled task.

Make sure the service name is the name of the actual service and not the display name for the service.

$logFile = "C:\test.csv"

$serviceName = "ServiceName";

$serviceStatus = (get-service "$serviceName").Status;

$date = Get-Date

$dateShort = $date.ToShortDateString()

$timeShort = $date.ToShortTimeString()

$i = 1

 

if ($serviceStatus -eq "Running") 

    {

        Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus"

    }

elseif ($serviceStatus -eq "Stopped") 

    {

 

            Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus, Starting"

            Start-Service $serviceName

        $serviceStatus = (get-service "$serviceName").Status;

        Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus"

            

    }

else 

    {

            Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus, Unable to Start"

    }

Leave a Comment

Your email address will not be published. Required fields are marked *