Windows - Add poll rest endpoint scheduled task

Octopus.Script exported 2018-07-17 by anatolie-darii belongs to ‘Windows’ category.

Adds a scheduled task that polls a specified endpoint at a specific interval using the provided HTTP method

Parameters

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

Endpoint Uri

AD_PollRestEndpoint_Uri =

The endpoint uri to poll

Task name

AD_PollRestEndpoint_Name = Polling task for endpoint

Task name without any special characters

HTTP Method

AD_PollRestEndpoint_HttpMethod = GET

The HTTP method to be used for calling the endpoint

Polling interval

AD_PollRestEndpoint_Interval = 60

Polling interval in seconds

Attempts

AD_PollRestEndpoint_Attempts = 5

Number of retry attempts in case the scheduling fails

Script body

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

# Running outside octopus
Param(
    [string] $AD_PollRestEndpoint_Uri,
    [string] $AD_PollRestEndpoint_Name = "Polling task for endpoint",
    [string] $AD_PollRestEndpoint_HttpMethod = "GET",
    [string] $AD_PollRestEndpoint_Interval = 60,
    [Int16] $AD_PollRestEndpoint_Attempts = 5,
    [switch] $WhatIf
)

$ErrorActionPreference = "Stop"

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($null -ne $OctopusParameters) {
        $result = $OctopusParameters[$Name]
    }

    if ($null -eq $result) {
        $variable = Get-Variable $Name -EA SilentlyContinue
        if ($null -ne $variable) {
            $result = $variable.Value
        }
    }

    if ($null -eq $result) {
        if ($Required) {
            throw "Missing parameter value $Name"
        }
        else {
            $result = $Default
        }
    }

    return $result
}
function Execute(
    [Parameter(Mandatory = $true)][string] $Uri,
    [Parameter(Mandatory = $false)][string] $Name = "Polling task for endpoint",
    [Parameter(Mandatory = $false)][string] $HttpMethod = "GET",
    [Parameter(Mandatory = $false)][string] $Interval = 60,
    [Parameter(Mandatory = $false)][Int16] $Attempts = 5
) {
    $attemptCount = 0
    $operationIncomplete = $true
    $maxFailures = $Attempts
    $sleepBetweenFailures = 1

    $script = '-noprofile -executionpolicy bypass -command "& { Invoke-RestMethod -Uri ' + $Uri + ' -Method ' + $HttpMethod + ' }"'
    $repeat = (New-TimeSpan -Seconds $Interval)

    $action = New-ScheduledTaskAction "powershell.exe" -Argument  "$script"
    $duration = (New-TimeSpan -Days 9999)
    $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat -RepetitionDuration $duration
    $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd

    while ($operationIncomplete -and $attemptCount -lt $maxFailures) {
        $attemptCount = ($attemptCount + 1)
        if ($attemptCount -ge 2) {
            Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..."
            Start-Sleep -s $sleepBetweenFailures
            Write-Output "Retrying..."
            $sleepBetweenFailures = ($sleepBetweenFailures * 2)
        }
        try {
            $task = Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue
            Write-Output $task
            $msg = "Task '$Name'"
            if ($null -ne $task) {
                Write-Output "$msg already exists - DELETING..."
                if (-Not ($WhatIf)) {
                    Unregister-ScheduledTask -TaskName $name -Confirm:$false
                }
                Write-Output "$msg - DELETED"
            }
            Write-Output "$msg - ADDING..."
            if (-Not ($WhatIf)) {
                Register-ScheduledTask -TaskName $Name -Action $action -Trigger $trigger -RunLevel Highest -Settings $settings -User "System"
            }
            Write-Output "$msg - ADDED"
            $operationIncomplete = $false
        }
        catch [System.Exception] {
            if ($attemptCount -lt ($maxFailures)) {
                Write-Host ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message)
            }
            else {
                throw
            }
        }
    }
}
& Execute `
(Get-Param 'AD_PollRestEndpoint_Uri' -Required)`
(Get-Param 'AD_PollRestEndpoint_Name')`
(Get-Param 'AD_PollRestEndpoint_HttpMethod')`
(Get-Param 'AD_PollRestEndpoint_Interval')`
(Get-Param 'AD_PollRestEndpoint_Attempts')

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": "0ad0ad00-adad-adad-adad-000000000002",
  "Name": "Windows - Add poll rest endpoint scheduled task",
  "Description": "Adds a scheduled task that polls a specified endpoint at a specific interval using the provided HTTP method",
  "Version": 1,
  "ExportedAt": "2018-07-17T10:18:23.003Z",
  "ActionType": "Octopus.Script",
  "Author": "anatolie-darii",
  "Parameters": [
    {
      "Name": "AD_PollRestEndpoint_Uri",
      "Label": "Endpoint Uri",
      "HelpText": "The endpoint uri to poll",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "AD_PollRestEndpoint_Name",
      "Label": "Task name",
      "HelpText": "Task name without any special characters",
      "DefaultValue": "Polling task for endpoint",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "AD_PollRestEndpoint_HttpMethod",
      "Label": "HTTP Method",
      "HelpText": "The HTTP method to be used for calling the endpoint",
      "DefaultValue": "GET",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "GET\nPOST\nPUT\nDELETE\nPATCH"
      }
    },
    {
      "Name": "AD_PollRestEndpoint_Interval",
      "Label": "Polling interval",
      "HelpText": "Polling interval in seconds",
      "DefaultValue": "60",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "AD_PollRestEndpoint_Attempts",
      "Label": "Attempts",
      "HelpText": "Number of retry attempts in case the scheduling fails",
      "DefaultValue": "5",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nParam(\n    [string] $AD_PollRestEndpoint_Uri,\n    [string] $AD_PollRestEndpoint_Name = \"Polling task for endpoint\",\n    [string] $AD_PollRestEndpoint_HttpMethod = \"GET\",\n    [string] $AD_PollRestEndpoint_Interval = 60,\n    [Int16] $AD_PollRestEndpoint_Attempts = 5,\n    [switch] $WhatIf\n)\n\n$ErrorActionPreference = \"Stop\"\n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($null -ne $OctopusParameters) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($null -eq $result) {\n        $variable = Get-Variable $Name -EA SilentlyContinue\n        if ($null -ne $variable) {\n            $result = $variable.Value\n        }\n    }\n\n    if ($null -eq $result) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        }\n        else {\n            $result = $Default\n        }\n    }\n\n    return $result\n}\nfunction Execute(\n    [Parameter(Mandatory = $true)][string] $Uri,\n    [Parameter(Mandatory = $false)][string] $Name = \"Polling task for endpoint\",\n    [Parameter(Mandatory = $false)][string] $HttpMethod = \"GET\",\n    [Parameter(Mandatory = $false)][string] $Interval = 60,\n    [Parameter(Mandatory = $false)][Int16] $Attempts = 5\n) {\n    $attemptCount = 0\n    $operationIncomplete = $true\n    $maxFailures = $Attempts\n    $sleepBetweenFailures = 1\n\n    $script = '-noprofile -executionpolicy bypass -command \"& { Invoke-RestMethod -Uri ' + $Uri + ' -Method ' + $HttpMethod + ' }\"'\n    $repeat = (New-TimeSpan -Seconds $Interval)\n\n    $action = New-ScheduledTaskAction \"powershell.exe\" -Argument  \"$script\"\n    $duration = (New-TimeSpan -Days 9999)\n    $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat -RepetitionDuration $duration\n    $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd\n\n    while ($operationIncomplete -and $attemptCount -lt $maxFailures) {\n        $attemptCount = ($attemptCount + 1)\n        if ($attemptCount -ge 2) {\n            Write-Output \"Waiting for $sleepBetweenFailures seconds before retrying...\"\n            Start-Sleep -s $sleepBetweenFailures\n            Write-Output \"Retrying...\"\n            $sleepBetweenFailures = ($sleepBetweenFailures * 2)\n        }\n        try {\n            $task = Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue\n            Write-Output $task\n            $msg = \"Task '$Name'\"\n            if ($null -ne $task) {\n                Write-Output \"$msg already exists - DELETING...\"\n                if (-Not ($WhatIf)) {\n                    Unregister-ScheduledTask -TaskName $name -Confirm:$false\n                }\n                Write-Output \"$msg - DELETED\"\n            }\n            Write-Output \"$msg - ADDING...\"\n            if (-Not ($WhatIf)) {\n                Register-ScheduledTask -TaskName $Name -Action $action -Trigger $trigger -RunLevel Highest -Settings $settings -User \"System\"\n            }\n            Write-Output \"$msg - ADDED\"\n            $operationIncomplete = $false\n        }\n        catch [System.Exception] {\n            if ($attemptCount -lt ($maxFailures)) {\n                Write-Host (\"Attempt $attemptCount of $maxFailures failed: \" + $_.Exception.Message)\n            }\n            else {\n                throw\n            }\n        }\n    }\n}\n& Execute `\n(Get-Param 'AD_PollRestEndpoint_Uri' -Required)`\n(Get-Param 'AD_PollRestEndpoint_Name')`\n(Get-Param 'AD_PollRestEndpoint_HttpMethod')`\n(Get-Param 'AD_PollRestEndpoint_Interval')`\n(Get-Param 'AD_PollRestEndpoint_Attempts')\n"
  },
  "Category": "Windows",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/windows-add-poll-endpoint-task.json",
  "Website": "/step-templates/0ad0ad00-adad-adad-adad-000000000002",
  "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 Tuesday, July 17, 2018