How To Stop, Start, Restart a Windows Service Being Stuck in ‘Stopping’ Status

Convenient Function:

function restartService($serviceName){
    $waitSeconds=40
    $isValidProcess=try{[bool](get-service $serviceName -EA Stop)}catch{$false}
    if($isValidProcess){
        try{
            $process=Start-Process -FilePath powershell.exe -ArgumentList "-Command Restart-Service $serviceName" -PassThru -NoNewWindow
            $process|Wait-Process -Timeout $waitSeconds -ErrorAction Stop
            return $true
        }catch{
            write-warning $_
            $process|Stop-Process -Force
            $processId=(get-process $serviceName).Id
            if($processId){
                write-host "Program now forcefully kills PID $processId of process $serviceName"
                $null=$processId|%{taskkill /f /pid $_} # works more reliably than Stop-Process $processName -Force
                Start-Service $serviceName -ErrorAction Ignore
                $started=$(try{get-service $serviceName}catch{$false})
                if($started){
                    write-host "'serviceName' status is now $($started.Status)"
                    return $true
                }else{
                    write-warning "'serviceName' status is $($started.Status)"
                    return $false
                }
            }else{
                write-warning "Service '$serviceName' PID not found."
                return $false         
            }
        }
    }
}
 
restartService vmms
Symptom:
# Example error of Hyper-V Virtual Machine Management Service
Service 'Hyper-V Virtual Machine Management (vmms)' cannot be stopped due to the following error: Cannot stop vmms
service on computer '.'.
+ CategoryInfo : CloseError: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.RestartServiceCommand
+ PSComputerName : HYPERV05
Resolution:
# Kill the process id prior to attempting to start the service
$serviceName='vmms'
$processId=(get-process $serviceName).Id
$null=taskkill /f /pid $processId
Start-Service $serviceName
PS C:\Windows\system32> taskkill /f /pid $processId
SUCCESS: The process with PID 21404 has been terminated.
PS C:\Windows\system32> restart-service vmms
WARNING: Waiting for service 'Hyper-V Virtual Machine Management (vmms)' to stop...
WARNING: Waiting for service 'Hyper-V Virtual Machine Management (vmms)' to stop...
WARNING: Waiting for service 'Hyper-V Virtual Machine Management (vmms)' to stop...
WARNING: Waiting for service 'Hyper-V Virtual Machine Management (vmms)' to stop...
WARNING: Waiting for service 'Hyper-V Virtual Machine Management (vmms)' to stop...

Leave a Reply

Your email address will not be published. Required fields are marked *