Functions/Private/Invoke-InfluxDbApi.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#requires -Version 4
#requires -Modules WebRequest

function Invoke-InfluxDbApi {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Query
        ,
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [Microsoft.PowerShell.Commands.WebRequestMethod]
        $Method = 'Get'
        ,
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]
        $Database
    )

    $InfluxDb = Get-InfluxDbServer

    $Url = "$($InfluxDb.Server)/query?pretty=true"
    $Url += "&q=$Query"
    if ($Database) {
        $Url += "&db=$Database"
    }

    $ConfiguredProtocols = [System.Net.ServicePointManager]::SecurityProtocol
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls11,Tls12'

    $Response = Invoke-AuthenticatedWebRequest -Uri $Url -Method $Method -User $InfluxDb.User -Token $InfluxDb.Token
    $Content = $Response.Content | ConvertFrom-Json
    
    [System.Net.ServicePointManager]::SecurityProtocol = $ConfiguredProtocols

    foreach ($Result in $Content.results.series) {
        $Name = $Result.name
        $Columns = $Result.columns
        $Values  = $Result.values
        for ($RowIndex = 0; $RowIndex -lt $Values.Length; ++$RowIndex) {
            $Row = @{}
            if ($Name.Length -gt 0 -and -not $Row.ContainsKey('series_name')) {
                $Row.Add('series_name', $Name)
            }
            for ($ColumnIndex = 0; $ColumnIndex -lt $Columns.Length; ++$ColumnIndex) {
                $Row.Add($Columns[$ColumnIndex], $Values[$RowIndex][$ColumnIndex])
            }
            [pscustomobject]$Row
        }
    }
}