Private/RestMethod.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
74
75
#
# Copyright 2018, Alexis La Goutte <alexis dot lagoutte at gmail dot com>
#
# SPDX-License-Identifier: Apache-2.0
#

function Invoke-NSXTRestMethod {

    <#
      .SYNOPSIS
      Invoke RestMethod with NSX-T connection (internal) variable
 
      .DESCRIPTION
      Invoke RestMethod with NSX-T connection variable (token,.)
 
      .EXAMPLE
      Invoke-NSXTRestMethod -method "get" -uri "api/v1/cluster/status"
 
      Invoke-RestMethod with NSX-T connection for get api/v1/cluster/status uri
    #>


    Param(
        [Parameter(Mandatory = $true, position = 1)]
        [String]$uri,
        [Parameter(Mandatory = $false)]
        [ValidateSet("GET", "PUT", "POST", "DELETE")]
        [String]$method = "GET",
        [Parameter(Mandatory = $false)]
        [psobject]$body,
        [Parameter(Mandatory = $false)]
        [psobject]$connection
    )

    Begin {
    }

    Process {

        if ($null -eq $connection ) {
            if ($null -eq $DefaultNSXTConnection){
                Throw "Not Connected. Connect to the NSX-T with Connect-NSXT"
            }
            $connection = $DefaultNSXTConnection
        }

        $Server = $connection.Server
        $port = $connection.port
        $headers = $connection.headers
        $invokeParams = $connection.invokeParams

        $fullurl = "https://${Server}:${port}/${uri}"

        #Extra parameter...
        if($fullurl -NotMatch "\?"){
            $fullurl += "?"
        }

        try {
            if ($body) {
                $response = Invoke-RestMethod $fullurl -Method $method -body ($body | ConvertTo-Json) -Headers $headers @invokeParams
            }
            else {
                $response = Invoke-RestMethod $fullurl -Method $method -Headers $headers @invokeParams
            }
        }

        catch {
            Show-NSXTException $_
            throw "Unable to use NSX-T API"
        }
        $response

    }

}