Friday, May 17, 2013

Use Powershell Script to Check Windows Service Services’ States

I have a bunch of windows servers running SQL servers. Want to make sure all windows services which are set to “Auto Start” are not stopped. Here is the powershell script to check them assuming we have all the server names in file DBServers.txt.

   1: $dbservers = get-content ".\DBServers.txt"
   2:  
   3: foreach ($Hostname in $dbservers) 
   4: {
   5:     Write-Host "Checking on server: $Hostname"
   6:  
   7:     $Services=get-wmiobject -class win32_service -computername $Hostname `
   8:             | where {$_.StartMode -eq "Auto" -and $_.Started -eq $false } `
   9:             | select-object Name,state,status,Started,StartMode,Startname,DisplayName
  10:  
  11:     foreach ( $service in $Services)
  12:     {
  13:         $message="[$Hostname] " +$Service.Name + " (" + $service.DisplayName + ") " +$Service.state +" " `
  14:                 +$Service.status +" " +$Service.Started +" " +$Service.Startname 
  15:         write-host $message -background "RED" -foreground "BLACK"     
  16:     }
  17: }
  18:  
  19: Write-Host "All checkings are done."

No comments: