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: 1-liner to obtain SSID and Password of Wireless Profiles on a Windows Machine

$profileName='Frontier0000'netsh wlan show profile "name=$profileName" key=clear|select-string "Key Content"# Sample outputKey Content : somepassword PS C:\Windows\system32>…

Server PDC Time Clock Synchronization 

Configuring the Windows Time service to use an external time source To configure an internal…

PowerShell: Methods to Download Files

# Change these values to reflect your desired downloads$fileURL = "https://download.microsoft.com/download/0/d/9/0d9d81cf-4ef2-4aa5-8cea-95a935ee09c9/PortQryV2.exe"$output = "C:\WINDOWS\System32\SysInternals\portqry.exe"1. Start-BitsTransfer (my…