private/Invoke-OneApiRequest.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
function Invoke-OneApiRequest {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory = $false)]
        [string] $ApiVersion = "beta",

        [Parameter(Mandatory = $true)]
        [string] $ApiResource,

        [Parameter(Mandatory = $true)]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $ApiRequestMethod,

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

    begin {
        Write-Verbose "[$(Get-Date)] [BEGIN ] $($MyInvocation.MyCommand)"
    }

    process {
        $ApiRequest = @{
            Uri = "https://graph.microsoft.com/$($ApiVersion)/$($ApiResource)"
            ContentType = "application/json"
            Headers = @{
                Authorization = "Bearer $($OneShortcutSession.Token.AccessToken)"
                Prefer = "apiversion=2.1"
            }
            Method = $ApiRequestMethod
        }
    
        if ($ApiRequestBody) {
            $ApiRequest.Body = $ApiRequestBody
        }

        $Api = @{
            Response = @{
                StatusCode = $null
                Message = $null
            }
            Data = $null   
        }
    
        try {
            Write-Verbose "[$(Get-Date)] [CALL ] Invoke-RestMethod($($ApiRequest.Uri), $($ApiRequest.ContentType), $($ApiRequest.Headers.Authorization), $($ApiRequest.Headers.Prefer), $($ApiRequest.Method), $($ApiRequest.Body))"
            $ApiResponse = (Invoke-WebRequest @ApiRequest)
            $ApiData = (ConvertFrom-Json $([String]::new($ApiResponse.Content)))

            $Api.Response.StatusCode = $ApiResponse.StatusCode
            $Api.Data = $ApiData
        } catch {
            $Api.Response.StatusCode = $_.Exception.Response.StatusCode.value__
            $Api.Response.Message = $_.Exception.Message
        }

        return $Api
    }

    end {
        Write-Verbose "[$(Get-Date)] [END ] $($MyInvocation.MyCommand)"
    }
}