Private/Invoke-bConnectGet.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Function Invoke-bConnectGet() {
    <#
        .Synopsis
            INTERNAL - HTTP-GET against bConnect
        .Parameter Data
            Hashtable with parameters
        .Parameter Version
            bConnect version to use
        .Parameter NoVersion
            Dont use a version in the request. Needed for "info" and "version"
    #>


    Param(
        [Parameter(Mandatory=$true)][string]$Controller,
        [PSCustomObject]$Data,
        [string]$Version,
        [switch]$NoVersion
    )

    If(!$script:_connectInitialized) {
        Write-Error "bConnect module is not initialized. Use 'Initialize-bConnect' first!"
        return $false
    }

    If([string]::IsNullOrEmpty($Version)) {
        $Version = $script:_bConnectFallbackVersion
    }

    If($verbose){
        $ProgressPreference = "Continue"
    } else {
        $ProgressPreference = "SilentlyContinue"
    }

    If($NoVersion) {
        $_uri = "$($script:_connectUri)/$($Controller)"
    } else {
        $_uri = "$($script:_connectUri)/$($Version)/$($Controller)"
    }

    try {
        If($Data.Count -gt 0) {
            $_rest = Invoke-RestMethod -Uri $_uri -Body $Data -Credential $script:_connectCredentials -Method Get -ContentType "application/json; charset=utf-8" -TimeoutSec $script:_ConnectionTimeout
        } else {
            $_rest = Invoke-RestMethod -Uri $_uri -Credential $script:_connectCredentials -Method Get -ContentType "application/json; charset=utf-8" -TimeoutSec $script:_ConnectionTimeout
        }

        If($_rest) {
            return $_rest
        } else {
            return $true
        }
    }

    catch {
        Try {
            $_response = ConvertFrom-Json $_
        }

        Catch {
            $_response = $false
        }

        If($_response) {
            Write-Error $_response.Message
        } else {
            Write-Error $_
        }

        return $false
    }
}