tim laqua dot com Thoughts and Code from Tim Laqua

15Apr/111

Restarting Automatic Services using Powershell

What? Why would you need to restart an automatic service? Because they die sometimes - there's probably some very good reasons for this, but I don't know them. What I do know is they die from time to time and don't come back. Sometimes they never get around to starting after a reboot.

I run the following Powershell script every 5 minutes to restart the ones that got tired:

#======= START Config ========
$emailServer = "1.2.3.4";
$fromAddress = "you@yourcompany.com";
$toAddress = "you@yourcompany.com";
$ignorePattern = '^(ShellHWDetection|MMCSS|sppsvc|clr_optimization.*)$';
#======== END Config =========
 
Get-WmiObject Win32_Service | 
? { 
  $_.StartMode -eq 'Auto' `
  -and $_.State -ne 'Running' `
  -and $_.Name -notmatch $ignorePattern
} | 
% { 
  $svcName = $_.Name; 
  $serverName = Get-Content env:computername;
  Start-Service -Name $_.Name -EA SilentlyContinue; 
  $smtp = new-object Net.Mail.SmtpClient($emailServer);
  $smtp.Send(
    "$serverName <$fromAddress>", 
    $toAddress, 
    "Started service ""$svcName""", 
    "Started service ""$svcName"" on $serverName.")
}

$ignorePattern is a regular expression for identifying what services to ignore (so services that you don't care to try and restart).

Comments (1) Trackbacks (0)
  1. “I run the following Powershell script every 5 minutes to restart the ones that got tired”

    are you running a script for that as well?


Leave a comment

No trackbacks yet.