Pingdom.Management.Checks.psm1

<#
.Synopsis
  Returns pingdom checks from the account associated with the provided AppKey
.Description
  Returns data for Pingdom uptime checks associated with the provided AppKey. Results can be filtered by tag.
.Example
  Get-PingdomCheck -AppKey $AppKey
  Returns all uptime checks in the Pingdom account associated with the provided AppKey
.Example
  Get-PingdomCheck -AppKey $AppKey -TagFilter 'Blue'
  Returns all uptime checks in the Pingdom account associated with the provided AppKey that are tagged with 'Blue'.
.Example
  Get-PingdomCheck -AppKey $AppKey -ID '123456'
  Returns data for Pingdom check with ID 123456.
.Parameter APIVersion
  Default: 3.1 Specifies the version of the API to use.
.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter ID
  If provided, filters results to the ID provided. Can be passed in via pipeline and pipeline by property name.
.Parameter PingdomURL
  The URL to pingdom's API
.Parameter TagFilter
  A string of comma seperated tag values that, when provided, filters returned checks to those containing the specified tags
#>

Function Get-PingdomCheck {
  [CmdletBinding(DefaultParameterSetName='Default')]
  Param (
  [Parameter (Mandatory = $true)]
  [string] $AppKey,
  [Parameter (ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, ParameterSetName = 'ID')]
  [String] $ID,
  [Parameter (ParameterSetName = 'Filter')]
  [string] $TagFilter,
  [string] $APIVersion = '3.1',
  [string] $PingdomURL = 'https://api.pingdom.com'
  )
  Begin {
    $BasePath = "/api/$APIVersion/checks"
    $Method = 'Get'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
  }
  Process {

    # Changes needed to meet the API spec when passing in an ID
    If ($ID) {
      $Path = "$BasePath/$ID"
      $Property = 'check'
    }
    Else {
      $Path = $BasePath
      $Property = 'checks'
    }

    # Build out the body of the request and account for a tag filter
    $Body = @{
      include_tags = $true
    }
    If ($TagFilter) {
      $Body += @{
        tags = $TagFilter
      }
    }

    # Send request to Pingdom and unwrap the results from the default container
    Return (Invoke-RestMethod -Method $Method -Uri "$PingdomURL$Path" -Headers $headers -Body $Body).$Property
  }
}
<#
.Synopsis
  Creates a new Pingdom uptime check
.Description
  Create a new Pingdom uptime check with the specified attributes
.Example
  New-PingdomCheck -AppKey $AppKey -Name 'MyUptimeCheck' -TargetHost 'mysite.com'
  Creates an uptime check using all default values to monitor https://mysite.com
.Example
  New-PingdomCheck -AppKey $AppKey -Name 'MyUptimeCheck' -TargetHost 'mysite.com' -TargetPath '/health/plain.html' -Tags 'Blue,Green,Yellow' -UserIDs '1234' -SendDownNotificationWhenDown 5 -Resolution 1
  Create an uptime check querying https://mysite.com/health/plain.html every 1 minute with tags 'Blue', 'Green', and 'Yellow' which will notify user ID 1234 if down after 5 consecutive failures
.Parameter APIVersion
  Default: 3.1 Specifies the version of the API to use.
.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter Name
  Name of the Pingdom check
.Parameter TargetHost
  The target host (e.g. google.com)
.Parameter APIVersion
  Version of the Pingdom API to use
.Parameter Encryption
  Default: True. Whether or not to use encryption for the connection, if this is an http check it forces HTTPS
.Parameter IntegrationIDs
  A comma seperated list of IntegrationIDs to notify immediately upon check status change (note: Integrations do not respect the SendNotificationWhenDown threshold)
.Parameter IPv6
  Default: False
  Use ipv6 instead of ipv4, if an IP address is provided as host this will be overrided by the IP address version
.Parameter NotifyAgainEvery
  Default: 0. Notify again every n result. 0 means that no extra notifications will be sent.
.Parameter NotifyWhenBackUp
  Default: True. Notify when back up again
.Parameter Paused
  Default: False. Whether the check should be paused. Paused checks do not probe and will not alert or count as downtime in reports.
.Parameter PingdomURL
  The URL to pingdom's API
.Parameter Port
  Specifies the exact port to use for this check
.Parameter PostData
  Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server.
.Parameter ProbeFilters
  Default: NA and EU. Restricts probes to the geographical region selected (North America = NA, Europe = EU, Asia Pacific = APAC, Latin America = LATAM). Provide a single region to probe from.
.Parameter Resolution
  Default: 5. How often the check gets probed in minutes. Allowed values are 1,5,15,30,60.
.Parameter ResponseTimeThreshold
  Default: 3000. How long to wait for a response before triggering an alert in ms.
.Parameter SendNotificationWhenDown
  Default = 2. Specifies the number of consecutive checks should fail before sending notifications. Note that integration IDs do not respect this setting.
.Parameter ShouldContain
  Text that the response should contain to pass the check
.Parameter ShouldNotContain
  Text that the response shouldnot contain to pass the check
.Parameter Tags
  String of comma seperated tags added to uptime check
.Parameter TargetPath
  The path to the check target including any query string parameters (e.g. /health/plain.html?format=json)
.Parameter TeamIDs
  A string of comma seperated Team IDs to alert for notifications
.Parameter Type
  Default: http. The type of check to create (can be http,httpcustom, tcp, ping, udp, smtp, pop3, imap)
.Parameter UserIDs
  A string of comma seperated userids to alert for notifications (these notifications DO respect ResponseTimeThreshold)
#>

Function New-PingdomCheck {

  [cmdletbinding(SupportsShouldProcess = $true)]
  Param (
  [Parameter (Mandatory = $true)]
  [string] $AppKey,
  [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
  [string] $Name,
  [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
  [string] $TargetHost,
  [string] $APIVersion = '3.1',
  [bool] $Encryption = $true,
  [string] $IntegrationIDs,
  [bool] $IPv6 = $false,
  [int] $NotifyAgainEvery = 0,
  [bool] $NotifyWhenBackUp = $true,
  [bool] $Paused = $false,
  [string] $PingdomURL = 'https://api.pingdom.com',
  [int] $Port,
  [string] $PostData,
  [ValidateSet('NA','EU','APAC','LATAM')]
  [string] $ProbeFilters,
  [ValidateSet(1,5,15,30,60)]
  [int] $Resolution = 5,
  [int] $ResponseTimeThreshold = 3000,
  [int] $SendNotificationWhenDown = 2,
  [string] $ShouldContain,
  [string] $ShouldNotContain,
  [string] $Tags,
  [string] $TargetPath,
  [string] $TeamIDs,
  [ValidateSet('http','httpcustom','tcp','ping','dns','udp','smtp','pop3','imap')]
  [string] $Type = 'http',
  [string] $UserIds
)
  Begin {
    $QueryString = "/api/$APIVersion/checks"
    $Method = 'POST'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
  }
  Process {
    # Add required syntax for probe filters
    If ($ProbeFilters) {
        [string]$ProbeFromRegion = "region:$ProbeFilters"
    }

    # Construct string body
    $Body = "encryption=$Encryption" + `
      "&host=$TargetHost" + `
      "&type=$Type" + `
      "&name=$Name" + `
      "&ipv6=$IPv6" + `
      "&notifyagainevery=$NotifyAgainEvery" + `
      "&notifywhenbackup=$NotifyWhenBackup" + `
      "&paused=$Paused" + `
      "&port=$Port" + `
      "&probe_filters=$ProbeFromRegion" + `
      "&resolution=$Resolution" + `
      "&responsetime_threshold=$ResponseTimeThreshold" + `
      "&sendnotificationwhendown=$SendNotificationWhenDown" + `
      "&tags=$Tags" + `
      "&teamids=$TeamIDs" + `
      "&userids=$UserIDs"

    # Add parameters that require values if passed to API
    If ($IntegrationIDs) {
      $Body+="&integrationids=$IntegrationIDs"
    }
    If ($ShouldContain) {
      $Body+="&shouldcontain=$ShouldContain"
    }
    If ($ShouldNotContain) {
      $Body+="&shouldnotcontain=$ShouldNotContain"
    }
    If ($PostData) {
      $Body+="&postdata=$PostData"
    }
    If ($TargetPath) {
      $Body += "&url=$TargetPath"
    }

    Write-Verbose "Sending attributes: $Body"
    If ($PSCmdlet.ShouldProcess($Name)) {
      Return (Invoke-RestMethod -Method $Method -Uri "$PingdomURL$QueryString" -Headers $headers -Body $Body).check
    }
  }
}


<#
.Synopsis
  Updates an existing Pingdom uptime check
.Description
  Updates an existing Pingdom uptime check with the specified attributes
.Example
  Update-PingdomCheckByID -AppKey $AppKey -ID '123456' -Tags 'Blue, Green,' -IntegrationID 'ABC12345'
  Updates an existing Pingdom uptime check and replaces any existing tags with 'Blue' and 'Green' and any existing integrations with 'ABC12345'
.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter APIVersion
  Version of the Pingdom API to use
.Parameter Encryption
  Whether or not to use encryption for the connection, if this is an http check it forces HTTPS
.Parameter IntegrationIDs
  A comma seperated list of IntegrationIDs to notify immediately upon check status change (note: Integrations do not respect the SendNotificationWhenDown threshold)
.Parameter IPv6
  Use ipv6 instead of ipv4, if an IP address is provided as host this will be overrided by the IP address version
.Parameter NotifyAgainEvery
  Notify again every n result. 0 means that no extra notifications will be sent.
.Parameter NotifyWhenBackUp
  Notify when back up again
.Parameter Paused
  Whether the check should be paused. Paused checks do not probe and will not alert or count as downtime in reports.
.Parameter PingdomURL
  The URL to pingdom's API
.Parameter Port
  Specifies the exact port to use for this check
.Parameter PostData
  Data that should be posted to the web page, for example submission data for a sign-up or login form. The data needs to be formatted in the same way as a web browser would send it to the web server.
.Parameter ProbeFilters
  Restricts probes to the geographical region selected (North America = NA, Europe = EU, Asia Pacific = APAC, Latin America = LATAM). Provide a single region to probe from.
.Parameter Resolution
  How often the check gets probed in minutes. Allowed values are 1,5,15,30,60.
.Parameter ResponseTimeThreshold
  How long to wait for a response before triggering an alert in ms.
.Parameter SendNotificationWhenDown
  Specifies the number of consecutive checks should fail before sending notifications. Note that integration IDs do not respect this setting.
.Parameter ShouldContain
  Text that the response should contain to pass the check
.Parameter ShouldNotContain
  Text that the response shouldnot contain to pass the check
.Parameter Tags
  String of comma seperated tags added to uptime check, overwrites any existing tags. Use TagsToAdd parameter to add new tags without overwriting existing tags.
.Parameter TagsToAdd
  String of comma seperated tags to add in addition to previously specified tags
.Parameter TargetPath
  The path to the check target including any query string parameters (e.g. /health/plain.html?format=json)
.Parameter TeamIDs
  A string of comma seperated Team IDs to alert for notifications
.Parameter UserIDs
  A string of comma seperated userids to alert for notifications (these notifications DO respect ResponseTimeThreshold)
#>

Function Update-PingdomCheckByID {
  [cmdletbinding(SupportsShouldProcess = $true)]
  Param (
    [Parameter (Mandatory = $true)]
    [string] $AppKey,
    [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
    [string] $ID,
    [string] $APIVersion = '3.1',
    [bool] $Encryption,
    [string] $IntegrationIDs,
    [bool] $IPv6,
    [string] $Name,
    [int] $NotifyAgainEvery,
    [bool] $NotifyWhenBackUp,
    [bool] $Paused,
    [string] $PingdomURL = 'https://api.pingdom.com',
    [int] $Port,
    [string] $PostData,
    [ValidateSet('NA','EU','APAC','LATAM')]
    [string] $ProbeFilters,
    [ValidateSet(1,5,15,30,60)]
    [int] $Resolution,
    [int] $ResponseTimeThreshold,
    [int] $SendNotificationWhenDown,
    [string] $ShouldContain,
    [string] $ShouldNotContain,
    [string] $Tags,
    [string] $TagsToAdd,
    [string] $TargetHost,
    [string] $TargetPath,
    [string] $TeamIDs,
    [string] $UserIds
  )
  Begin {
    $Method = 'PUT'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
  }
  Process {
    $QueryString = "/api/$APIVersion/checks/$ID"

    # This gets the names of all parameters to which arguments were explicitly passed on invocation
    $Attributes = $PSBoundParameters.Keys
    Write-Verbose "Parameters passed to function: $Attributes"

    # Iterate over the list of parameters and build the body
    Foreach ($Attribute in $Attributes) {

      # This adds the appropriate &'s without any additional
      If ($Body -and $Body[-1] -ne '&') {
        $Body += '&'
      }

      # Add the appropriate body statement for the attribute specified
      Switch ($Attribute) {
        "Encryption" {$Body += "encryption=$Encryption"}
        "IntegrationIDs" {$Body += "integrationids=$IntegrationIDs"}
        "IPV6" {$Body += "ipv6=$IPv6"}
        "Name" {$Body += "name=$Name"}
        "NotifyAgainEvery" {$Body += "notifyagainevery=$NotifyAgainEvery"}
        "NotifyWhenBackup" {$Body += "notifywhenbackup=$NotifyWhenBackup"}
        "Paused" {$Body += "paused=$Paused"}
        "Port" {$Body += "port=$Port"}
        "ProbeFilters" {$Body += "probe_filters=region:$ProbeFilters"}
        "Resolution" {$Body += "resolution=$Resolution"}
        "ResponseTimeThreshold" {$Body += "responsetime_threshold=$ResponseTimeThreshold"}
        "SendNotificationWhenDown" {$Body += "sendnotificationwhendown=$SendNotificationWhenDown"}
        "TargetHost" {$Body += "host=$TargetHost"}
        "TargetPath" {$Body += "url=$TargetPath"}
        "Tags" {$Body += "tags=$Tags"}
        "TeamIDs" {$Body += "teamids=$TeamIDs"}
        "UserIDs" {$Body += "userids=$UserIDs"}
      }
    }
    Write-Verbose "Sending Body: $Body"
    If ($PSCmdlet.ShouldProcess($ID)) {
      Invoke-RestMethod -Method $Method -Uri "$PingdomURL$QueryString" -Headers $headers -Body $Body
    }
  }
}

<#
.Synopsis
  Removes a Pingdom check
.Description
  Permanently deletes a Pingdom check
.Example
  Remove-PingdomCheck -AppKey $AppKey -ID '123456'
  Permanently deletes the Pingdom check with ID 123456
.Example
  $IDs | Remove-PingdomCheck -AppKey $AppKey
  Permanently deletes all check IDs contained in $IDs.
.Parameter APIVersion
  Default: 3.1 Specifies the version of the API to use.
.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter ID
  If provided, filters results to the ID provided. Can be passed in via pipeline and pipeline by property name.
.Parameter PingdomURL
  The URL to pingdom's API
#>

Function Remove-PingdomCheck {
  [cmdletbinding(SupportsShouldProcess = $true)]
  Param (
    [Parameter (Mandatory = $true)]
    [string] $AppKey,
    [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)]
    [string] $ID,
    [string] $PingdomURL = 'https://api.pingdom.com',
    [string] $APIVersion = '3.1'
  )
  Begin {
    $Path = "/api/$APIVersion/checks"
    $Method = 'Delete'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
  }
  Process {
    [array]$CheckIDs += $ID
  }
  End {
    $Body = @{
      delcheckids = $CheckIDs -join (',')
    }
    If ($PSCmdlet.ShouldProcess($ID)) {
      Write-Verbose "Sending request to $PingdomURL$Path"
      Return Invoke-RestMethod -Method $Method -Uri "$PingdomURL$Path" -Headers $headers -Body $Body
    }
  }
}

<#
.Synopsis
  Returns the number of down time events.
.Description
  Returns the number of down time events over a given time period.
.Example
  Get-PingdomCheckOutageCount -AppKey $AppKey -ID 12345 -From 10/01/2020 -To 11/01/2020
  Returns the total number of times the check had a down status event between 10/01/2020 - 11/01/2020
.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter APIVersion
  Version of the Pingdom API to use
.Parameter From
  The PowerShell date/time to start the report from, defaults to 01/01/1970
.Parameter PingdomURL
  The URL to pingdom's API
.Parameter ID
  Required. Returns the result for the check ID provided.
.Parameter To
  The Powershell date/time to end the report from, defaults to current time

#>


Function Get-PingdomCheckOutageCount {
  [CmdletBinding(DefaultParameterSetName='Default')]
  Param (
    [Parameter (Mandatory = $true)]
    [string] $AppKey,
    [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)]
    [String] $ID,
    [datetime] $From = (Get-Date "01/01/1970"),
    [String] $Order = 'asc',
    [datetime] $To = (Get-Date),
    [string] $APIVersion = '3.1',
    [string] $PingdomURL = 'https://api.pingdom.com'
  )
  Begin {
    $BasePath = "/api/$APIVersion/summary.outage/$ID"
    $Method = 'Get'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
  }
  Process {
    # Convert Dates to EPOCH
    $unixFrom = [int32](New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date $From)).TotalSeconds
    $unixTo = [int32](New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date $To)).TotalSeconds
    $Path = "$BasePath/?from=$unixFrom&order=$Order&To=$unixTo"
    # Send request to Pingdom and unwrap the results from the default container
    Return ((Invoke-RestMethod -Method $Method -Uri "$PingdomURL$Path" -Headers $headers -Body $Body).summary.states | Where-Object {$_.status -eq 'down'}).count
  }
}

<#
.Synopsis
  Returns the uptime percentage for a probe.
.Description
  Returns the uptime percentage for a probe over a given time period.
.Example

  Get-PingdomCheckUptime -AppKey $AppKey -ID 12345 -From 10/01/2020 -To 11/01/2020
  Returns the total uptime, downtime, and uptime percentage of check with ID 12345 from 10/01/2020 to 11/1/2020.

.Parameter AppKey
  The API key used to access the Pingdom API
.Parameter APIVersion
  Version of the Pingdom API to use
.Parameter From
  The unix timestamp of the date to start the uptime analysis. Defaults to 0 (01/01/1970). This is an integer representing the number of seconds since 01/01/1970 until the from date/time.
.Parameter PingdomURL
  The URL to pingdom's API
.Parameter ID
  Filters results to the ID provided. Can be passed in via pipeline and pipeline by property name.
.Parameter To
  The unix timestamp of the date to end the uptime analysis. Defaults to current time. This is an integer representing the number of seconds since 01/01/1970 until the to date/time.
#>

Function Get-PingdomCheckUptime {
  [CmdletBinding(DefaultParameterSetName='Default')]
  Param (
  [Parameter (Mandatory = $true)]
  [string] $AppKey,
  [Parameter (Mandatory = $true, ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)]
  [String] $ID,
  [datetime] $From,
  [datetime] $To,
  [string] $APIVersion = '3.1',
  [string] $PingdomURL = 'https://api.pingdom.com'
  )
  Begin {
    $BasePath = "/api/$APIVersion/summary.average"
    $Method = 'Get'
    $headers = @{
      Authorization = "Bearer $AppKey"
    }
    If ($From) {
      $UnixFrom = [int32](New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date $From)).TotalSeconds
    }
    If ($To) {
      $UnixTo = [int32](New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date $To)).TotalSeconds
    }
  }
  Process {
    $Path = "$BasePath/$($ID)?includeuptime=true"
      If ($From) {
        $Path += "&from=$UnixFrom"
      }
      If ($To) {
        $Path += "&to=$UnixTo"
      }

    # Send request to Pingdom and unwrap the results from the default container
    Return (Invoke-RestMethod -Method $Method -Uri "$PingdomURL$Path" -Headers $headers -Body $Body).summary
  }
}