cancel
Showing results for 
Search instead for 
Did you mean: 

A little powershell script to restart a service

Slartybardfast
Level 5

Oops Sorry All

I posted the wrong script. This is the correct one that uses a function. Enjoy

Snip Code Begin

function Stop-PendingService {

    $Services = Get-WmiObject -Class win32_service -Filter "state = 'stop pending'"
    if ($Services) {
        foreach ($service in $Services) {
            try {
                Stop-Process -Id $service.processid -Force -PassThru -ErrorAction Stop
            }
            catch {
                Write-Warning -Message "Unexpected Error. Error details: $_.Exception.Message"
            }
        }
    }
    else {
        Write-Output "There are currently no services with a status of 'Stopping'."
    }
}

$service = Get-Service -Name "<YourServiceHere>"
$service.Stop()
$Service.WaitForStatus('Stopped','00:05:00')
if ($service.Status -eq 'Stop pending'){Stop-PendingService}
    elseif($service.Status -eq 'Stopped'){$service.Start()}

Snip Code End

0 REPLIES 0