Tuesday, September 6, 2022

Powershellscript to get details of Azure users who have synced to Azure with diferent upn

 # Connecting to Azure Parameters
$tenantID = "mytenantid"
$ClientId = "myapplicationid"
$ClientSecret = "myclientsecret"



# Create a hashtable for the body, the data needed for the token request
# The variables used are explained above
$Body = @{
    'tenant' = $TenantId
    'client_id' = $ClientId
    'scope' = 'https://graph.microsoft.com/.default'
    'client_secret' = $ClientSecret
    'grant_type' = 'client_credentials'
}

# Assemble a hashtable for splatting parameters, for readability
# The tenant id is used in the uri of the request as well as the body
$Params = @{
    'Uri' = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
    'Method' = 'Post'
    'Body' = $Body
    'ContentType' = 'application/x-www-form-urlencoded'
}

$AuthResponse = Invoke-RestMethod @Params

$Headers = @{
    'Authorization' = "Bearer $($AuthResponse.access_token)"
}

#$url = "https://graph.microsoft.com/v1.0/users/?$select=displayName,givenName,postalCode,UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName"

$url = 'https://graph.microsoft.com/v1.0/users/?$select=UserPrincipalName,onPremisesDistinguishedName,onPremisesUserPrincipalName'

$userPurpose = @()

$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $url


$nexturl = $UserData.'@odata.nextLink'
$userPurpose+= $UserData
$count = 0
while($nexturl -ne "")
{

$nexturl = $UserData.'@odata.nextLink'
Write-host $nexturl -ForegroundColor Yellow
if(!$nexturl) {break;}
$UserData = Invoke-RestMethod -Method GET -headers $headers -Uri $nexturl


$userPurpose+= $UserData
$count++

}

 Write-host "Count of url: $count" -ForegroundColor Yellow

 $userPurpose.count

 $Users = @()
 Foreach($userdata in $userPurpose)
 {
   $Users+=$userdata.value
 }

$users | Export-csv -Path c:\temp\Azureusers1.csv -NoClobber -NoTypeInformation -Append

No comments:

Post a Comment