Private/Webrequest.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#
# Copyright 2018, Alexis La Goutte <alexis dot lagoutte at gmail dot com>
#
# SPDX-License-Identifier: Apache-2.0
#
function Invoke-ArubaSWWebRequest() {

    <#
      .SYNOPSIS
      Invoke WebRequest with ArubaSW connection (internal) variable
 
      .DESCRIPTION
       Invoke WebRequest with ArubaSW connection variable (IP Address, cookie, port...)
 
      .EXAMPLE
      Invoke-ArubaSWWebRequest -method "get" -uri "rest/v4/vlan"
 
      Invoke-WebRequest with ArubaSW connection for get rest/v4/vlan
 
      .EXAMPLE
      Invoke-ArubaSWWebRequest "rest/v1/system"
 
      Invoke-WebRequest with ArubaSW connection for get rest/v1/system uri with default GET method parameter
 
      .EXAMPLE
      Invoke-ArubaSWWebRequest -method "post" -uri "rest/v1/system" -body $body
 
      Invoke-WebRequest with ArubaSW connection for post rest/v1/system uri with $body payload
 
      .EXAMPLE
      Invoke-ArubaSWWebRequest -method "get" -uri "rest/v1/system" -depth 1 -selector configuration
 
      Invoke-WebRequest with ArubaSW connection for get rest/v1/system with depth 1 and select only configuration
 
    #>



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

    Begin {
    }

    Process {

        if ($null -eq $connection ) {
            if ($null -eq $DefaultArubaSWConnection){
                Throw "Not Connected. Connect to the Switch with Connect-ArubaSW"
            }
            $connection = $DefaultArubaSWConnection
        }

        $Server = $connection.Server
        $httpOnly = $connection.httpOnly
        $port = $connection.port
        $invokeParams = $connection.InvokeParams
        $sessionvariable = $connection.session

        if ($httpOnly) {
            $fullurl = "http://${Server}:${port}/${uri}"
        }
        else {
            $fullurl = "https://${Server}:${port}/${uri}"
        }

        try {
            if ($body) {
                $response = Invoke-WebRequest $fullurl -Method $method -body ($body | ConvertTo-Json) -Websession $sessionvariable @invokeParams
            }
            else {
                $response = Invoke-WebRequest $fullurl -Method $method -Websession $sessionvariable @invokeParams
            }
        }
        catch {
            Show-ArubaSWException -Exception $_
            throw "Unable to use switch API"
        }
        $response

    }

}