PowerShell Script To Restart Service And Dependents

Some of my Windows 2008 R2 servers have been reaching over our 80% committed memory threshold more often than preferred. There is a hotfix out as noted on Kevin Holman’s OpsMgr Blog – http://blogs.technet.com/b/kevinholman/archive/2010/06/09/wmi-leaks-memory-on-server-2008-r2-monitored-agents.aspx , however the server admins have not tested and deployed the hotfix yet so in the mean time I needed an efficient way to bounce the WMI service along with dependencies.

In case anyone else if having this issue… This is the script I am using as a Recovery Task with Winmgmt as its parameter to run and sorry if I made any mistakes this is only my third PowerShell script! Feel free to change and let me know if there is a better way! .. NOTE: You will probably need to sign the code unless you changed the PowerShell script execution policy to Unrestricted !

Sponsors, article continues below...
####################################################
## Usage: RestartService.ps1 <service name> ########
## Author: Stephen Leuthold (http://blogmynog.com) #
## Created: 6/22/2010 ##############################
## Modified: 6/22/2010 #############################
## Purpose: Restart service and dependencies #######
####################################################
 
PARAM($svcName)
 
# Get dependent services
$depSvcs = Get-Service -name $svcName -dependentservices | Where-Object {$_.Status -eq "Running"} |Select -Property Name
 
# Check to see if dependent services are started
if ($depSvc -ne $null) {
	# Stop dependencies
	foreach ($depSvc in $depSvcs)
	{
		Stop-Service $depSvc.Name
		do
		{
			$service = Get-Service -name $depSvc.Name | Select -Property Status
			Start-Sleep -seconds 1
		}
		until ($service.Status -eq "Stopped")
	}
}
 
# Restart service
Restart-Service $svcName -force
do
{
	$service = Get-Service -name $svcName | Select -Property Status
	Start-Sleep -seconds 1
}
until ($service.Status -eq "Running")
 
 
$depSvcs = Get-Service -name $svcName -dependentservices |Select -Property Name
 
# We check for Auto start flag on dependent services and start them even if they were stopped before
foreach ($depSvc in $depSvcs)
{
	$startMode = gwmi win32_service -filter "NAME = '$($depSvc.Name)'" | Select -Property StartMode
	if ($startMode.StartMode -eq "Auto") {
		Start-Service $depSvc.Name
		do
		{
			$service = Get-Service -name $depSvc.Name | Select -Property Status
			Start-Sleep -seconds 1
		}
		until ($service.Status -eq "Running")
	}
}
This entry was posted in Microsoft, PowerShell, SCOM.

2 Responses to PowerShell Script To Restart Service And Dependents

  1. Pingback: Adding A Basic PowerShell recovery to a Monitor | Living with SCOM

  2. Pingback: Automation Scripting PowerShell: Servicios, SSRS, etc « El TecnoBaúl de Kiquenet

Leave a Reply