Posted On February 2, 2023

PowerShell: Kill a Windows Service Forcefully

kimconnect 0 comments
blog.KimConnect.com >> Codes , Windows >> PowerShell: Kill a Windows Service Forcefully
# killService.ps1
$serviceName='vmms'

function killService($serviceName='Spooler',$restart=$false){    
    $processId=Get-WmiObject -Class Win32_Service -Filter "Name LIKE '$serviceName'"|Select-Object -ExpandProperty ProcessId
    if($processId.count -eq 1 -and $processId -ne 0){
        try{
            $taskkill=taskkill /f /pid $processid
            write-host $taskkill
            if($restart){
                start-service $serviceName
                $result=get-service $serviceName
                if($result.Status -eq 'Running'){
                    $processId=Get-WmiObject -Class Win32_Service -Filter "Name LIKE '$serviceName'"|Select-Object -ExpandProperty ProcessId
                    write-host "$serviceName has successfully restarted with pid $processId" -foregroundcolor GREEN
                    return $true
                }else{
                    write-host "$serviceName has NOT successfully restarted" -foregroundcolor RED
                    return $false
                }
            }else{
                $result=get-service $serviceName
                if($result.Status -eq 'Stopped'){
                    $processId=Get-WmiObject -Class Win32_Service -Filter "Name LIKE '$serviceName'"|Select-Object -ExpandProperty ProcessId
                    write-host "$serviceName has successfully stopped" -foregroundcolor GREEN
                    return $true
                }else{
                    write-host "$serviceName has NOT successfully stopped" -foregroundcolor RED
                    return $false
                }
            }            
        }catch{
            write-warning $_
            return $false
        }
    }else{
        try{
            start-service $serviceName
        }catch{
            write-warning $_
            # write-warning "$serviceName is not found on $env:computername"
            return $null
        }
        
    }
}

killService $serviceName

Leave a Reply

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

Related Post

Transfer DHCP Scopes Between Windows Servers

When a new DHCP server is introduced into the system, it's often necessary to configure…

On Premise Exchange to Office 365 Migration Using Method: Asynchronous PST Export & Import

Assumptions: 1. Hybrid Exchange Migration and Stage Migration methods have been considered and rejected2. Active…

Use PowerShell to Get GeoLocation of a Computer’s Public IP

Method 1: Invoke-RestMethod -Uri ('http://ipinfo.io/'+(Invoke-WebRequest -uri "http://ifconfig.me/ip").Content) Method 2: function getIPGeolocation($ipAddress) {$request = Invoke-RestMethod -Method…