现在的位置: 首页 > 综合 > 正文

Restart-Service (recursively)

2012年12月07日 ⁄ 综合 ⁄ 共 1999字 ⁄ 字号 评论关闭
文章目录

Restart-Service (recursively)

http://bsonposh.com/archives/545

I often need to restart services on multiple machines and one of the biggest issues is the dependent services that also need to be restarted. I finally found time to write a script that will recursively stop and start dependent services.

Parameters:

  • ServiceName: Name of the Service to restart (REQUIRED)
  • Server: Name of the Server to restart the service on (Default is local server)
  • Verbose: Enable verbose output

More Info:
System.ServiceProcess.ServiceController

Restart-Service


Param($ServiceName = $(throw ‘$ServiceName is Required’),
      $Server = $Env:ComputerName,
      [Switch]$Verbose)

 

$VerbosePreference = "Continue"

[system.Reflection.Assembly]::LoadWithPartialName("System.ServiceProcess") | out-Null

$ErrorActionPreference = "SilentlyContinue"

Write-Verbose " – ServiceName = $ServiceName"
Write-Verbose " – Server = $Server"

function Get-Dependents{
    Param([System.ServiceProcess.ServiceController]$MasterService)
    Write-Verbose "   + Getting Dependent Services for $($MasterService.Name)"
    foreach($dependent in $MasterService.DependentServices)
    {
        Write-Verbose "     – Found Dependent Service [$($dependent.Name)]"
        $dependent
        Get-Dependents $dependent
    }
}

Write-Verbose " – Getting Service [$ServiceName]"
$Service = New-Object System.ServiceProcess.ServiceController($ServiceName,$Server)

Write-Verbose " – Getting Dependent Services"
$DependentServices = Get-Dependents $Service

Write-Verbose " + Stopping [$ServiceName] and dependent Services"
$Service.Stop()

Write-Verbose "   – Waiting for Service to Stop"
$Service.WaitForStatus("Stopped",(new-object system.TimeSpan(0,0,20)))

Write-Verbose " + Starting [$ServiceName]"
$Service.Start()

Write-Verbose "   – Waiting for Service to Start"
$Service.WaitForStatus("Running",(new-object system.TimeSpan(0,0,20)))

foreach($dependent in $DependentServices )
{
    $dependent.Refresh()
    if($dependent.status -eq "Stopped")
    {
        $dependent.Start()
        $dependent.WaitForStatus("Running",(new-object system.TimeSpan(0,0,5)))
    }
}
$Service.Refresh()
$Service
$Service.DependentServices

Trackback this post | Feed on Comments to this post

抱歉!评论已关闭.