# 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