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

PowerShell: Script to Apply Windows Update on 2016 Server

8/7/2020: there's a more updated version available here. # Update-Remote-Windows-2016-Servers.ps1$servers="SERVER1","SERVER2"function applyWindowsUpdates{ [CmdletBinding()] param ( [parameter(Mandatory=$true,Position=1)]…

G729 Codec

cd /usr/lib/asterisk/moduleswget http://asterisk.hosting.lv/mv codec_g729-ast110-gcc4-glibc-x86_64-core2.so codec_g729.sochmod 755 codec_g729.soamportal restartasterisk -rx "core show codecs"Download these two files:1.…

HAProxy with Multiple SSL Certs

Method 1: --------- defaults   log 127.0.0.1 local0   option tcplog   frontend ft_test   mode http   bind…