Stop Service With Kill

Octopus.Script exported 2018-11-05 by benjimac93 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 ($svc -eq $null) { return $true }
        if ($svc.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped) { return $true }
        $svc.Stop()
        try {
            Write-Host "Stopping Service" $svcTimeout "Timeout"
            $svc.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, $timespan)
        }
        catch [ServiceProcess.TimeoutException] {
            Write-Host "Timeout stopping service $($svc.Name)"
            return $false
        }
        Write-Host "Service Sucessfully stopped"
        return $true

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

Write-Host "Checking service"

$svcpid = (get-wmiobject Win32_Service | where{$_.Name -eq $svcName}).ProcessId
Write-Host "Found PID " + $svcpid 

Stop-ServiceWithTimeout -name $svcName -timeoutSeconds $svcTimeout

Write-Host "Rechecking service"
$svcpid = (get-wmiobject Win32_Service | where{$_.Name -eq $svcName}).ProcessId
Write-Host "Found PID " + $svcpid 

$service = Get-Service -name $svcName | Select -Property Status
if($service.Status -ne "Stopped"){	Start-Sleep -seconds 5 }

#Check-Service process 
if($svcpid){
    #still exists?
    $p = get-process -id $svcpid -ErrorAction SilentlyContinue
    if($p){
        Write-Host "Killing Service"
        Stop-Process $p.Id -force
    }
}

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": 8,
  "ExportedAt": "2018-11-05T03:59:57.028Z",
  "ActionType": "Octopus.Script",
  "Author": "benjimac93",
  "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 ($svc -eq $null) { return $true }\n        if ($svc.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped) { return $true }\n        $svc.Stop()\n        try {\n            Write-Host \"Stopping Service\" $svcTimeout \"Timeout\"\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        Write-Host \"Service Sucessfully stopped\"\n        return $true\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\"\n\n$svcpid = (get-wmiobject Win32_Service | where{$_.Name -eq $svcName}).ProcessId\nWrite-Host \"Found PID \" + $svcpid \n\nStop-ServiceWithTimeout -name $svcName -timeoutSeconds $svcTimeout\n\nWrite-Host \"Rechecking service\"\n$svcpid = (get-wmiobject Win32_Service | where{$_.Name -eq $svcName}).ProcessId\nWrite-Host \"Found PID \" + $svcpid \n\n$service = Get-Service -name $svcName | Select -Property Status\nif($service.Status -ne \"Stopped\"){\tStart-Sleep -seconds 5 }\n\n#Check-Service process \nif($svcpid){\n    #still exists?\n    $p = get-process -id $svcpid -ErrorAction SilentlyContinue\n    if($p){\n        Write-Host \"Killing Service\"\n        Stop-Process $p.Id -force\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