Skip to content

Instantly share code, notes, and snippets.

@bmatthewshea
Last active September 20, 2022 15:45
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 bmatthewshea/b3be68faadf754161c09638b6b10b75b to your computer and use it in GitHub Desktop.
Save bmatthewshea/b3be68faadf754161c09638b6b10b75b to your computer and use it in GitHub Desktop.
Query and restart a Windows service as needed. (PowerShell)
<#
Script: "check-restart-windows-service.ps1"
Query and restart service as needed.
Use task scheduler with this script.
Brady M. Shea - 16 Sep 2022
.Setting $ServiceName
.Find the service name to monitor by opening a PS command prompt and entering "GET-SERVICE"
.Setting $SleepSecs
.If your service needs very little time to start, you could set this to 0. But, setting higher will hurt nothing.
#>
# Edit these
$ServiceName = 'MyServiceName'
$SleepSecs = 5
# Edit these ends
function IsAdminUser
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if (!(IsAdminUser)) {
write-host "This script needs to be run with Administrator credentials. Exiting." -Fore red
exit
}
try {
$arrService = Get-Service -Name $ServiceName -ErrorAction Stop
} catch {
write-host 'ERROR: Service name does not exist. Exiting.'
exit
}
$DisplayServiceName = $arrService.DisplayName
if ($arrService.Status -ne 'Running') {
while ($arrService.Status -ne 'Running') {
Start-Service $ServiceName
write-host $arrService.Status
write-host "SERVICE DOWN! Service starting. Waiting $SleepSecs seconds...`n"
Start-Sleep -seconds $SleepSecs
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host "$DisplayServiceName is now running again."
}
else
{
Write-Host "$DisplayServiceName failed to start!"
}
}
}
else {
Write-Host "$DisplayServiceName is already running. Exiting."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment