Functions/Shared/Invoke-MSGraphRequest.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
Function Invoke-MSGraphRequest
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)]
        [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = 'Default',

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.Uri]$Uri,
        
        [Parameter(Mandatory = $false)]
        [Object]$Body,
        
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.Collections.IDictionary]$Headers,
        
        [Parameter(Mandatory = $false)]
        [System.String]$ContentType = 'application/json'
    )

    $Params = @{
        Method = $Method
        Uri = $Uri
        ContentType = $ContentType
        #ErrorAction = 'Stop'
    }
    
    if ($Headers) {
        $Params['Headers'] = $Headers
    } else {
        $Params['Headers'] = @{ }
    }
    if (!$global:PowerGraph_AccessToken)
    {
        throw "Access token not found - please connect to your Microsoft Graph account first using the 'Connect-MSGraph' command"
    }

    $Params['Headers']['Authorization'] = 'Bearer {0}' -f $global:PowerGraph_AccessToken.AccessToken
    
    if ([string]::IsNullOrEmpty($Body) -eq $false)
        { $Params['Body'] = $Body }

    try {

        $Result = Invoke-WebRequest @Params -UseBasicParsing -ErrorAction Ignore

        Write-Verbose "Graph Response: $($Result.Content)"

        $returnValue = $Result.Content | ConvertFrom-Json -ErrorAction SilentlyContinue

        return $returnValue

    }
    catch {
        if ($_.Exception.Response -ne $null)
        {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader $responseStream
            $responseBody = $streamReader.ReadToEnd()

            if ($_.Exception.Response.StatusCode -eq "Unauthorized") # 401
                { $hint = " [Hint: The request you are making might not be possible using the authentication model you've selected. Review the api reference for the command you're trying to execute at https://developer.microsoft.com/en-us/graph/docs/api-reference and verify that the permission does not say 'Not supported.'. If it does, you might need to call Connect-MSGraph with a username and password first instead.] " }

            if ($_.Exception.Response.StatusCode -eq "Forbidden") # 403
                { $hint = " [Hint: You might need to get an updated Admin consent if you've recently changed the application's permissions. ] " }
        } else
            { $responseBody = "" }

        Write-Error ($_.Exception.Message + $hint + " " + $responseBody)
    }
}