internal/functions/Invoke-AzureAdRequest.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
function Invoke-AzureAdRequest
{
<#
    .SYNOPSIS
        Execute an arbitrary graph call against AzureAD endpoints.
     
    .DESCRIPTION
        Execute an arbitrary graph call against AzureAD endpoints.
        Handles authentication & token refresh transparently.
     
    .PARAMETER Query
        The actual query to execute.
     
    .PARAMETER Method
        The REST method to apply
     
    .PARAMETER Body
        Any body data to pass along as part of the request
     
    .PARAMETER GetValues
        Get the content of the .Value property, rather than the raw response content
     
    .PARAMETER Raw
        Get raw response
     
    .EXAMPLE
        PS C:\> Invoke-AzureAdRequest -Query 'users/3ec9f2ec-aeec-4ad9-ad18-b456288fdb32/authentication/phonemethods' -Method GET
         
        Retrieve the phone authentication settings for the specified user.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Query,
        
        [Parameter(Mandatory = $true)]
        [string]
        $Method,
        
        $Body,
        
        [switch]
        $GetValues,
        
        [switch]
        $Raw
    )
    
    begin
    {
        try { $authHeader = Get-Token | ConvertTo-AuthHeader }
        catch { throw }
        
        $parameters = @{
            Method = $Method
            Uri    = "$($script:baseUri.Trim("/"))/$($Query.TrimStart("/"))"
            Headers = $authHeader
        }
        if ($Body) { $parameters.Body = $Body }
    }
    process
    {
        try { $response = Invoke-RestMethod @parameters -ErrorAction Stop }
        catch { throw }
        
        
        if ($Raw) { return $response }
        if ($GetValues) { return $response.Value }
        $response.Value
        
    }
}