Restart IIS With Powershell
[system.Reflection.Assembly]::LoadWithPartialName("System.ServiceProcess") | out-Null
function Get-ServiceStartupMode
{
param([string]$servicename,[string]$serverName)
$startMode= gwmi win32_service -filter "NAME = '$servicename'" -computername $serverName | Select -Property StartMode
$startMode
}
function Get-DependentServices{
Param([System.ServiceProcess.ServiceController]$MasterService)
foreach($dependent in $MasterService.DependentServices)
{
$dependent
Get-DependentServices $dependent
}
}
function Restart-MainServices
{
Param($ServiceName = $(throw ‘$ServiceName is Required’))
process
{
$Service = New-Object System.ServiceProcess.ServiceController($ServiceName,$_)
$DependentServices = Get-DependentServices $Service
if($Service.CanStop)
{
$Service.Stop()
$Service.WaitForStatus("Stopped",(new-object system.TimeSpan(0,0,20)))
}
if($Service.status -eq "Stopped")
{
Write-Host "===Main Service:$($Service.name) start==="
$Service.Start()
$Service.WaitForStatus("Running",(new-object system.TimeSpan(0,0,30)))
}
foreach($dependent in $DependentServices )
{
$dependent.Refresh()
$startMode= Get-ServiceStartupMode -servicename $dependent.name -serverName $_
if($startMode.StartMode -eq "Auto")
{
Write-Host "===dependent Service:$($dependent.name) start==="+ $startMode.StartMode
if($dependent.status -ne "Running")
{
$dependent.Start()
$dependent.WaitForStatus("Running",(new-object system.TimeSpan(0,0,30)))
}
}
}
$Service.Refresh()
$Service
$Service.DependentServices
}
}