Private/Invoke-PASRestMethod.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
function Invoke-PASRestMethod {
    <#
    .SYNOPSIS
    Wrapper for Invoke-WebRequest to call REST method via API

    .DESCRIPTION
    Sends requests to web services. Catches Exceptions. Outputs Success.
    Acts as wrapper for the Invoke-WebRequest CmdLet so that status codes can be
    queried and acted on.
    All requests are sent with ContentType=application/json.
    If the sessionVariable parameter is passed, the function will return the WebSession
    object to the $Script:WebSession variable.

    .PARAMETER Method
    The method for the REST Method.
    Only accepts GET, POST, PUT, PATCH or DELETE

    .PARAMETER URI
    The address of the API or service to send the request to.

    .PARAMETER Body
    The body of the request to send to the API

    .PARAMETER Headers
    The header of the request to send to the API.

    .PARAMETER SessionVariable
    If passed, will be sent to invoke-webrequest which in turn will create a websession
    variable using the string value as the name. This variable will only exist in the current scope
    so will be set as the value of $Script:WebSession to be available in a modules scope.
    Cannot be specified with WebSession

    .PARAMETER WebSession
    Accepts a WebRequestSession object containing session details
    Cannot be specified with SessionVariable

    .PARAMETER UseDefaultCredentials
    See Invoke-WebRequest
    Used for Integrated Auth

    .PARAMETER TimeoutSec
    See Invoke-WebRequest
    Specify a timeout value in seconds

    .PARAMETER CertificateThumbprint
    See Invoke-WebRequest
    The thumbprint of the certificate to use for client certificate authentication.

    .EXAMPLE
    Invoke-PASRestMethod -Uri $URI -Method DELETE -WebSession $Script:WebSession

    Send request to web service
    #>

    [CmdletBinding(DefaultParameterSetName = "WebSession")]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('GET', 'POST', 'PUT', 'DELETE', 'PATCH')]
        [String]$Method,

        [Parameter(Mandatory = $true)]
        [String]$URI,

        [Parameter(Mandatory = $false)]
        [String]$Body,

        [Parameter(Mandatory = $false)]
        [hashtable]$Headers,

        [Parameter(
            Mandatory = $false,
            ParameterSetName = "SessionVariable"
        )]
        [String]$SessionVariable,

        [Parameter(
            Mandatory = $false,
            ParameterSetName = "WebSession"
        )]
        [Microsoft.PowerShell.Commands.WebRequestSession]$WebSession,

        [Parameter(Mandatory = $false)]
        [switch]$UseDefaultCredentials,

        [Parameter(Mandatory = $false)]
        [int]$TimeoutSec,

        [Parameter(Mandatory = $false)]
        [string]$CertificateThumbprint
    )

    Begin {

        #Set defaults for all function calls
        $PSBoundParameters.Add("ContentType", 'application/json')
        $PSBoundParameters.Add("UseBasicParsing", $true)

        #Bypass strict RFC header parsing in PS Core
        #Use TLS 1.2
        if ($IsCoreCLR) {

            $PSBoundParameters.Add("SkipHeaderValidation", $true)
            $PSBoundParameters.Add("SslProtocol", "TLS12")

        }

        #If Tls12 Security Protocol is available
        if (([Net.SecurityProtocolType].GetEnumNames() -contains "Tls12") -and

            #And Tls12 is not already in use
            (-not ([System.Net.ServicePointManager]::SecurityProtocol -match "Tls12"))) {

            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        }

    }

    Process {

        #Show sanitised request body if in debug mode
        If ([System.Management.Automation.ActionPreference]::SilentlyContinue -ne $DebugPreference) {

            If ($PSBoundParameters.ContainsKey("Body")) {

                Write-Debug "[Body] $(Hide-SecretValue -InputValue $Body)"

            }

        }

        try {

            #make web request, splat PSBoundParameters
            $APIResponse = Invoke-WebRequest @PSBoundParameters -ErrorAction Stop

        } catch [System.UriFormatException] {

            #Catch URI Format errors. Likely $Script:BaseURI is not set; New-PASSession should be run.
            $PSCmdlet.ThrowTerminatingError(

                [System.Management.Automation.ErrorRecord]::new(

                    "$PSItem Run New-PASSession",
                    $null,
                    [System.Management.Automation.ErrorCategory]::NotSpecified,
                    $PSItem

                )

            )

        } catch {

            $ErrorID = $null
            $StatusCode = $($PSItem.Exception.Response).StatusCode.value__
            $ErrorMessage = $($PSItem.Exception.Message)

            $Response = $PSItem.Exception | Select-Object -ExpandProperty 'Response' -ErrorAction Ignore
            if ( $Response ) {

                $ErrorDetails = $($PSItem.ErrorDetails)
            }

            # Not an exception making the request or the failed request didn't have a response body.
            if ( $null -eq $ErrorDetails ) {

                throw $PSItem

            } Else {

                If (-not($StatusCode)) {

                    #Generic failure message if no status code/response
                    $ErrorMessage = "Error contacting $($PSItem.TargetObject.RequestUri.AbsoluteUri)"

                } ElseIf ($ErrorDetails) {

                    try {

                        #Convert ErrorDetails JSON to Object
                        $Response = $ErrorDetails | ConvertFrom-Json
                        #API Error Message
                        $ErrorMessage = "[$StatusCode] $($Response.ErrorMessage)"
                        #API Error Code
                        $ErrorID = $Response.ErrorCode

                    } catch {

                        #If error converting JSON, return $ErrorDetails
                        #replace any new lines or whitespace with single spaces
                        $ErrorMessage = $ErrorDetails -replace "(`n|\W+)", " "
                        #Use $StatusCode as ErrorID
                        $ErrorID = $StatusCode

                    }
                }

            }

            #throw the error
            $PSCmdlet.ThrowTerminatingError(

                [System.Management.Automation.ErrorRecord]::new(

                    $ErrorMessage,
                    $ErrorID,
                    [System.Management.Automation.ErrorCategory]::NotSpecified,
                    $PSItem

                )

            )

        } finally {

            #If Command Succeeded
            if ($?) {

                #If Session Variable passed as argument
                If ($PSCmdlet.ParameterSetName -eq "SessionVariable") {

                    #Make the WebSession available in the module scope
                    Set-Variable -Name WebSession -Value $(Get-Variable $(Get-Variable sessionVariable).Value).Value -Scope Script

                }

                #Status code indicates success
                If ($APIResponse.StatusCode -match '^20\d$') {

                    #Pass APIResponse to Get-PASResponse
                    $APIResponse | Get-PASResponse

                }

            }

        }

    }

    End { }

}