powershellinvoke-restmethod

Powershell Invoke-RestMethod Paging


I am trying to get a list of all users from our Azure B2C tenant.

With some help from the internet I was able to create the powershell script below. But the result is incomplete it only shows 100 users. After searching around I found I should probably do something with Paging but I can't get it to work.

Can someone help me to modify the script below to return all users?

# Application (client) ID, tenant Name and secret
$clientId = "**********"
$tenantName = "*********"
$clientSecret = "************"
$resource = "https://graph.microsoft.com/"


$ReqTokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    client_Id     = $clientID
    Client_Secret = $clientSecret
} 

$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody


$Url = "https://graph.microsoft.com/beta/users?$select=displayName"
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $Url -Method Get
$Users = ($Data |select-object Value).Value

$Users | Format-Table DisplayName -AutoSize

Solution

  • Ok i got it to work in Powershell Core (Version 7.1.3).

    This is the code I ended up using.

    # Application (client) ID, tenant Name and secret
    $clientId = "**************"
    $tenantName = "***************"
    $clientSecret = "******************"
    $resource = "https://graph.microsoft.com/"
    
    
    $ReqTokenBody = @{
        Grant_Type    = "client_credentials"
        Scope         = "https://graph.microsoft.com/.default"
        client_Id     = $clientID
        Client_Secret = $clientSecret
    } 
    
    $TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
    
    $Url = "https://graph.microsoft.com/beta/users?$select=displayName"
    $UserResponse = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $Url -Method Get -Verbose
    
    $CloudUser = $UserResponse.Value
    $UserNextLink = $UserResponse."@odata.nextLink"
    
    while ($UserNextLink -ne $null) {
    
        $UserResponse = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $UserNextLink -Method Get -Verbose)
        $UserNextLink = $UserResponse."@odata.nextLink"
        $CloudUser += $UserResponse.value
    }
    
    $CloudUser | Format-Table DisplayName -AutoSize