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

function Invoke-ArubaCPRestMethod {

    <#
      .SYNOPSIS
      Invoke RestMethod with ArubaCP connection (internal) variable
 
      .DESCRIPTION
       Invoke RestMethod with ArubaCP connection variable (token, csrf..)
 
      .EXAMPLE
      Invoke-ArubaCPRestMethod -method "get" -uri "api/cppm-version"
 
      Invoke-RestMethod with ArubaCP connection for get api/cppm-version
 
      .EXAMPLE
      Invoke-ArubaCPRestMethod "api/cppm-version"
 
      Invoke-RestMethod with ArubaCP connection for get api/cppm-version uri with default GET method parameter
 
      .EXAMPLE
      Invoke-ArubaCPRestMethod -method "post" -uri "api/cppm-version" -body $body
 
      Invoke-RestMethod with ArubaCP connection for post api/cppm-version uri with $body payload
    #>


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

    Begin {
    }

    Process {

        $Server = ${DefaultArubaCPConnection}.Server
        $fullurl = "https://${Server}/${uri}"

        #When headers, We need to have Accept and Content-type set to application/json...
        $headers = @{ Authorization = "Bearer " + $DefaultArubaCPConnection.token; Accept = "application/json"; "Content-type" = "application/json" }

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

        catch {
            Show-ArubaCPException $_
            throw "Unable to use ClearPass API"
        }
        $response

    }

}