Private/Curanet/Invoke-CuraDNSRequest.ps1

function Invoke-CuraDNSRequest {
    <#
        .SYNOPSIS
            Creates a webrequest against Curanet DNS Api.
            Checks if access_token is set or needs to be updated.
 
        .PARAMETER Uri
            String object containing the URI of the endpoint trying to be reached.
         
        .PARAMETER Method
            String object containing the request method.
         
        .PARAMETER Payload
            JSON object containing the payload.
 
        .OUTPUTS
            Object containing DNS object or error.
         
        .NOTES
            Should not be called manually except if you know what you're doing.
    #>

    param (
        [Parameter()]
        $Uri,

        [Parameter()]
        $Method = 'GET',

        [Parameter()]
        $Payload = ''
    )

    if( ($null -eq $global:DNSApiTokenExpire) -or ((Get-Date) -gt ($global:DNSApiTokenExpire)) ) {
        Get-CuraDNSApiToken
    }

    $BaseUrl = "https://api.curanet.dk/dns/v2"

    $Headers = @{
        Authorization = "bearer $($global:DNSApiToken.access_token)"
    }

    $FinalUri = "$($BaseUrl)/$($Uri)"

    if ($psversionTable.PSVersion.Major -gt 5 ) {

        if ($Payload -ne '') {
            $result = Invoke-RestMethod -Uri $FinalUri -Headers $headers -Method $Method -Body $Payload -ContentType 'application/json' -SkipHttpErrorCheck
        }

        else {
            $result = Invoke-RestMethod -Uri $FinalUri -Headers $headers -Method $Method -ContentType 'application/json' -SkipHttpErrorCheck
        }
        
    }
    else {
        try {
            if ($Payload -ne '') {
                $result = Invoke-WebRequest -Uri $FinalUri -Headers $headers -Method $Method -Body $Payload -ContentType 'application/json' -UseBasicParsing
            }

            else {
                $result = Invoke-WebRequest -Uri $FinalUri -Headers $headers -Method $Method -ContentType 'application/json' -UseBasicParsing
            }
        }
        catch {
            return ConvertFrom-JSON $($_.ErrorDetails)
        }
    }

    return $result
}