Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# Adding the AD AuthN library to your PowerShell Session.
# the default path to where the ADAL GraphAPI PS Module puts the Libs
Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureADPreview\\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# Your Azure tenant name
$tenantID = ""
$authString = "$tenantID"
# username and password. The username must be MFA disabled user Admin at least, and must not be a live id.
$username = ""
$password = "S3cretSqu1rr3l"
# The resource URI for your token.
$resource = ""
# Object Type (eg. Users, Groups, Contacts)
$object = "users"
# This is the powershell common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
# Create a client credential with the above common client id, username and password.
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
# Create a authentication context with the above authentication string.
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
# Acquire access token from server.
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# Use the access token to setup headers for your http request.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = @{"Authorization"=$authHeader; "Content-Type"="application/json"}
# URI to get first 999 objects
$url = "{0}/$($object)?`$top=999&api-version=1.6"
# URI to page remainder of objects
$url2 = "$resource$tenantId/"
# Get the first 999 objects
$query = Invoke-RestMethod -Method Get -Headers @{
Authorization = $authenticationResult.CreateAuthorizationHeader()
'Content-Type' = "application/json"
} -Uri ($url -f $authenticationResult.TenantId)
# An Array for the retuned objects to go into
$tenantObjects = @()
# Add in our first 999 objects
$tenantObjects += $query.value
$moreObjects = $query
# Get all the remaining objects in 999 batches
if ($query.'odata.nextLink'){
$moreObjects.'odata.nextLink' = $query.'odata.nextLink'
$moreObjects = Invoke-RestMethod -Method Get -Headers @{
Authorization = $authenticationResult.CreateAuthorizationHeader()
'Content-Type' = "application/json"
} -Uri ($url2+$moreObjects.'odata.nextLink'+'&$top=999&api-version=1.6' -f $authenticationResult.TenantId)
$tenantObjects += $moreObjects.value
} while ($moreObjects.'odata.nextLink')
$tenantObjects | Out-GridView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.