Public/Tasks/Invoke-KillServiceTask.ps1

#Requires -Modules SitecoreInstallFramework

Set-StrictMode -Version Latest

Write-Verbose "Loading $($MyInvocation.MyCommand.Path)"

Function Invoke-KillServiceTask {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Name
    )

    Invoke-ManageServiceTask -Name $Name -Status 'Stopped' -PostDelay 20000 -ErrorAction SilentlyContinue -WhatIf:$WhatIfPreference   

    $service = Get-WmiObject -Query "select * from win32_service where name='$Name'"

    if ($service -and $service.State -eq 'Running') {
        [int]$processId = $null
        try {
            $processId = $service.ProcessId
        } catch {
            Write-Warning $_.Exception.Message
        }

        if ($processId) {
            $message = "Killing Service $Name [$processId]"
            if ($PSCmdLet.ShouldProcess("$name", "$message" )) {
                Write-TaskInfo $message -Tag 'KillService'
                Invoke-KillProcessTask -processId $processId
            }
        }
    } else {
        Write-TaskInfo "$Name does not exist" -Tag 'KillService'
    }
}
Register-SitecoreInstallExtension -Command Invoke-KillServiceTask -As KillService -Type Task -Force

Write-Verbose "Loaded $($MyInvocation.MyCommand.Path)"