Skip to content

Instantly share code, notes, and snippets.

@tjmichael81
Last active October 26, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjmichael81/5165e3354f92466e170fbadd3155b834 to your computer and use it in GitHub Desktop.
Save tjmichael81/5165e3354f92466e170fbadd3155b834 to your computer and use it in GitHub Desktop.
Basic PowerShell script to check the status of a Windows service, and start the service if the status is 'Stopped'
#requires -version 2
<#
.SYNOPSIS
PowerShell script to check the status of a Windows service, and start the service if status is 'Stopped'
.DESCRIPTION
PowerShell script to check the status of a Windows service, and start the service if status is 'Stopped'
.PARAMETER <Parameter_Name>
None
.INPUTS
$WindowsService: Name of target Windows service
.OUTPUTS
Log file stored in C:\Windows\Scripts\<name>.log>
.NOTES
Version: 1.0
Author: Tim Michael
Creation Date: 10/23/2018
Purpose/Change: Initial script development
.EXAMPLE
None
.RESOURCES
Powershell Script Template: https://gist.github.com/9to5IT/9620683
Logging Function: https://stackoverflow.com/questions/7834656/create-log-file-in-powershell
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
#Set Error Action to Silently Continue
#$ErrorActionPreference = "SilentlyContinue"
#Dot Source required Function Libraries
#. "C:\Scripts\Functions\Logging_Functions.ps1"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
#Script Version
$sScriptVersion = "1.0"
# Windows Service
$WindowsService = Get-Service -Name QBCFMonitorService
# Timestamp
$TimeStamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
# Log File
$Logfile = "C:\Windows\Scripts\QBServiceChecker\QBServiceChecker.log"
#-----------------------------------------------------------[Functions]------------------------------------------------------------
Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
}
#-----------------------------------------------------------[Execution]------------------------------------------------------------
# Get current status of service
# Write status to log file
$CurrentStatus = $WindowsService.Status
LogWrite($TimeStamp, ": Service is", $CurrentStatus)
# Start the service if the current status is Stopped
# Following start commant, re-check status and write to log file
If($WindowsService.Status -eq 'Stopped') {
Start-Service -Name $WindowsService.Name
Start-Sleep -Seconds 20
$WindowsService = Get-Service -Name QBCFMonitorService
$UpdatedTimeStamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$UpdatedStatus = $qbserv.Status
LogWrite($UpdatedTimeStamp, ": Service is", $UpdatedStatus)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment