Automated Dynatrace API data dumps from PowerShell

There are many ways to do this. I wrote this in Python and now PowerShell. The original was a bat file. PowerShell is easier to work with than bat/cmd f since they can be touchy with quoted strings and html encoding. This PowerShell gets the job done for both v1 and v2 and has a incremented datestamp.

<#
Automated Dynatrace data dumps.
Author: Charles Nichols, 2019
#>
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
 
$DynaHost = "YOUR_HOST"
$Token    = 'YOUR_TOKEN'
$DataType = 'application/json'
 
$BasePath = "c:\json" # Your preferred root path.
$IncrVal = 86400000   # Timestamp increment value for v1.
 
# ==============================================
#                 **** MAIN ****
# ==============================================
if (!(Test-Path $BasePath)) {
    New-Item -Path $BasePath -ItemType directory
}
 
# Read in previous timestamps
Try {
    $prev_dates = Get-Content -Path "$BasePath\dyna_dates.dat"
    $StartDt = [int]$prev_dates[0]
    $EndDt   = [int]$prev_dates[1]
} Catch {
    $StartDt = 1572580801000 # These could be set to just grab the current date, set here manually.
    $EndDt   = 1572667141000 # or manually create the file with your starts/end values.
}
 
# Increment the date range for v1...
$StartRange = $StartDt + $IncrVal
$EndRange   = $EndDt   + $IncrVal
 
# Write out new values.
$curr_dates = @($StartRange.ToString(),$EndRange.ToString())
$curr_dates | Set-Content -Path "$BasePath\dyna_dates.dat"
 
$URLS = @{
    "$($BasePath)\metrics1.json";"https://$($DynaHost)/c/********-1849-4837-8e18-8bc962f*****/api/v2/metrics/...",
    "$($BasePath)\metrics2.json";"https://$($DynaHost)/c/********-1849-4837-8e18-8bc962f*****/api/v2/metrics/...",
    "$($BasePath)\users1.json";"https://$($DynaHost)/c/********-1849-4837-8e18-8bc962f*****/api/v1/userSessionQueryLanguage/table?query=YOUR_QUERY&startTimestamp=$($StartRange)&endTimestamp=$($EndRange)&explain=false",
    "$($BasePath)\users2.json";"https://$($DynaHost)/c/********-1849-4837-8e18-8bc962f*****/api/v1/userSessionQueryLanguage/table?query=YOUR_QUERY&startTimestamp=$($StartRange)&endTimestamp=$($EndRange)&explain=false"
}
 
$headers = @{
    'accept' = $DataType
    'Authorization' = $Token
}
 
$Resp = $null
 
ForEach ($OutPath in $URLS.Keys()) {
 
    $url = $URLS[$OutPath]
    Write-Host "Working on: $url"
       
    (Invoke-WebRequest -Uri $url -Method GET -Headers $headers).Content | Out-File -FilePath $OutPath