Last active
September 20, 2022 15:45
-
-
Save bmatthewshea/b3be68faadf754161c09638b6b10b75b to your computer and use it in GitHub Desktop.
Query and restart a Windows service as needed. (PowerShell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
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