Stop Service With Kill

Octopus.Script exported 2018-11-05 by Bjoern-Hennings belongs to ‘Windows’ category.

This steps stops the specified service and in case it does not respond or times out, the service will be killed.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Service Name

ServiceName =

Name of the service to stop

Service Stop Timeout

ServiceStopTimeout = 10

Amount of time in seconds to wait before killing the Process

Script body

Steps based on this template will execute the following PowerShell script.

$svcName = $OctopusParameters['ServiceName']
$svcTimeout = $OctopusParameters['ServiceStopTimeout']

function Stop-ServiceWithTimeout ([string] $name, [int] $timeoutSeconds) {
    $timespan = New-Object -TypeName System.Timespan -ArgumentList 0,0,$timeoutSeconds

    If ($svc = Get-Service $svcName -ErrorAction SilentlyContinue) {
        if ($null -eq $svc) { return $true }
        if ($svc.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped) { return $true }
        try {
            Write-Host "Stopping Service with Timeout" $svcTimeout "seconds"
            $svc.Stop()
            $svc.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, $timespan)
        }
        catch [ServiceProcess.TimeoutException] {
            Write-Host "Timeout stopping service $($svc.Name)"
            return $false
        }
        catch {
            Write-Warning "Service $svcName could not be stopped: $_"
        }
        Write-Host "Service Sucessfully stopped"

    } Else {
        Write-Host "Service does not exist, this is acceptable. Probably the first time deploying to this target"
        Exit
    }
}

Write-Host "Checking service $svcName"
try {
    $svc = Get-Service $svcName
}
catch {
    if ($null -eq $svc) { Write-Warning "Service $svcName not found." }
    exit 1
}

$svcpid1 = (get-wmiobject Win32_Service | Where-Object{$_.Name -eq $svcName}).ProcessId
if($svcpid1 -ne 0) {
    Write-Host "Found PID $svcpid1 - stopping service now..."
    Stop-ServiceWithTimeout -name $svcName -timeoutSeconds $svcTimeout
}
else {
    Write-Host "No PID found for $svcName - service is already stopped."
    exit 0
}

Write-Host "Rechecking service"
$svcpid2 = (get-wmiobject Win32_Service | Where-Object{$_.Name -eq $svcName}).ProcessId
if($svcpid2 -eq 0) {
    Write-Host "no PID found for $svcName"
}
else {
    Write-Warning "PID $svcpid2 found for $svcName - service not stopped. Trying to Kill the process."
}

$service = Get-Service -name $svcName | Select-Object -Property Status
if($service.Status -ne "Stopped"){
    Start-Sleep -seconds 5
    $p = get-process -id $svcpid2 -ErrorAction SilentlyContinue
    if($p){
        Write-Host "Killing PID" $p.id "(" $p.Name ")"
        try {
            Stop-Process $p.Id -force
        }
        catch {
            Write-Warning "process" $p.id "could not be stopped:" $_
        }
    }
}

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "6fa0fab6-4799-4d81-944d-3c7b54530870",
  "Name": "Stop Service With Kill",
  "Description": "This steps stops the specified service and in case it does not respond or times out, the service will be killed.",
  "Version": 9,
  "ExportedAt": "2018-11-05T03:59:57.0280000Z",
  "ActionType": "Octopus.Script",
  "Author": "Bjoern-Hennings",
  "Packages": [],
  "Parameters": [
    {
      "Id": "7ad7cec6-c5c8-40a9-8657-793f88ea1c0f",
      "Name": "ServiceName",
      "Label": "Service Name",
      "HelpText": "Name of the service to stop",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "2ece0f23-76b7-490d-808f-64e5612ac0eb",
      "Name": "ServiceStopTimeout",
      "Label": "Service Stop Timeout",
      "HelpText": "Amount of time in seconds to wait before killing the Process",
      "DefaultValue": "10",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "$svcName = $OctopusParameters['ServiceName']\n$svcTimeout = $OctopusParameters['ServiceStopTimeout']\n\nfunction Stop-ServiceWithTimeout ([string] $name, [int] $timeoutSeconds) {\n    $timespan = New-Object -TypeName System.Timespan -ArgumentList 0,0,$timeoutSeconds\n\n    If ($svc = Get-Service $svcName -ErrorAction SilentlyContinue) {\n        if ($null -eq $svc) { return $true }\n        if ($svc.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped) { return $true }\n        try {\n            Write-Host \"Stopping Service with Timeout\" $svcTimeout \"seconds\"\n            $svc.Stop()\n            $svc.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, $timespan)\n        }\n        catch [ServiceProcess.TimeoutException] {\n            Write-Host \"Timeout stopping service $($svc.Name)\"\n            return $false\n        }\n        catch {\n            Write-Warning \"Service $svcName could not be stopped: $_\"\n        }\n        Write-Host \"Service Sucessfully stopped\"\n\n    } Else {\n        Write-Host \"Service does not exist, this is acceptable. Probably the first time deploying to this target\"\n        Exit\n    }\n}\n\nWrite-Host \"Checking service $svcName\"\ntry {\n    $svc = Get-Service $svcName\n}\ncatch {\n    if ($null -eq $svc) { Write-Warning \"Service $svcName not found.\" }\n    exit 1\n}\n\n$svcpid1 = (get-wmiobject Win32_Service | Where-Object{$_.Name -eq $svcName}).ProcessId\nif($svcpid1 -ne 0) {\n    Write-Host \"Found PID $svcpid1 - stopping service now...\"\n    Stop-ServiceWithTimeout -name $svcName -timeoutSeconds $svcTimeout\n}\nelse {\n    Write-Host \"No PID found for $svcName - service is already stopped.\"\n    exit 0\n}\n\nWrite-Host \"Rechecking service\"\n$svcpid2 = (get-wmiobject Win32_Service | Where-Object{$_.Name -eq $svcName}).ProcessId\nif($svcpid2 -eq 0) {\n    Write-Host \"no PID found for $svcName\"\n}\nelse {\n    Write-Warning \"PID $svcpid2 found for $svcName - service not stopped. Trying to Kill the process.\"\n}\n\n$service = Get-Service -name $svcName | Select-Object -Property Status\nif($service.Status -ne \"Stopped\"){\n    Start-Sleep -seconds 5\n    $p = get-process -id $svcpid2 -ErrorAction SilentlyContinue\n    if($p){\n        Write-Host \"Killing PID\" $p.id \"(\" $p.Name \")\"\n        try {\n            Stop-Process $p.Id -force\n        }\n        catch {\n            Write-Warning \"process\" $p.id \"could not be stopped:\" $_\n        }\n    }\n}\n",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline"
  },
  "Category": "Windows",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/windows-service-stop-or-kill.json",
  "Website": "/step-templates/6fa0fab6-4799-4d81-944d-3c7b54530870",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////Da3qSsLvhtb0wur6O7zuWcfxldv2aMzyK7ftpOD3s+X48Pr+0fD7d9HzHLLr4fX8xD/OcwAAAaNJREFUeNrs3cFygjAUQFECWott1f//2sJoW6kIKEzNs+euXOmcmSSGDa8oJEmSJEmSJGmsj1W1K9cpsGD1Vr2WdToVEPC+2lYvZfpVrEW0qZpF1F+MRdRugzoNlvkiarfBPk0pT8GhWUSX2yASpDlLr2+DEJBmEY1ug6whx7N0n2b30G1QlmmxHsRYp6X76yvF9vg5RYQczq8UVURI35UiFmTgShED0p6lI1eKzCHTrxS5Qk6PZ9PLDtJ9PIsJmXWlyAky6/dAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQMJCyjltF/iO3gpJUpD8s4OAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgID8T8itwwKyhbTdMr4ha8hXUwZqhICcOgyNOIkE+V5wo4MSgr1u/fp7poO+AL8K/gL8yw0UeyRB34m9iQ/pVD8L5JYTO3NI58R+AsiEEzsW5OfE3sUe/zRwYkeGnG2g2CPS7rhjF4GKP0ZwyoldxK37kFqEL/7wU0mSJEmSJOmJ+xRgAHxZTCXGdZkfAAAAAElFTkSuQmCC",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Monday, November 5, 2018