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 Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>