User OnPremisesExtensionAttributes from MS Graph

OnPremisesExtensionAttributes are not exposed by AAD PowerShell cmdlets, but they can be read from MS Graph.

https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list

My requirement is for reporting, so i need all the User objects with selected properties. For this we need an AAD App with User.Read.All permissions to MS Graph.

$ProgressPreference = "SilentlyContinue" # Azure Function App
<#
    Brearer token for the application
    Tenant can be found from (token_endpoint)
        https://login.windows.net/<yourdomain>.onmicrosoft.com/.well-known/openid-configuration
    $AccessToken
#>

$Tenant = ""
$AADGraphAppId = ""
$AADGraphAppKey = ""

$Body = @{
        "grant_type" = "client_credentials"
        "resource" = "https://graph.microsoft.com"
        "client_id" = $AADGraphAppId
        "client_secret" = $AADGraphAppKey
    }

$AppReq = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token" -Method Post -Body $Body
$AccessToken = $AppReq.access_token

After having the proper Bearer token, call MS Graph to get all users.


<#
    Loop all pages to get all Users
    Modify $select to get different properties
        onPremisesExtensionAttributes
    All Users will be included in the $UserData
#>
$Header = @{
    "Content-Type"="application\json"
    "Authorization"="Bearer $access_token"
    }

$Next = "https://graph.microsoft.com/v1.0/users?`$select=userprincipalname,onPremisesExtensionAttributes"

$UserData = @()
DO {
    $Data = Invoke-RestMethod -Uri $Next -Method Get -Headers $Header
    $UserData += $Data.value
    $Next = $Data.'@odata.nextLink'
} While ($Next)

Data can be then saved as a CSV for reporting

<#
    You can then export the Users to a csv and upload it to Azure Blob or another file drive
    Nice file paths include
        For Azure Functions

        Local
            "$Env:TEMP\userOnPremisesExtensionAttributes_$(get-date -format yyyy-MM-dd).csv"
#>
$YourPathWithFileExtension = "$execution_context_functiondirectory\userOnPremisesExtensionAttributes_$(get-date -format yyyy-MM-dd).csv"
$UserData | Select-Object -Property userprincipalname -ExpandProperty onPremisesExtensionAttributes | 
            Select-Object userprincipalname,extensionAttribute1,extensionAttribute2,extensionAttribute3,extensionAttribute4,extensionAttribute5,extensionAttribute6,extensionAttribute7,extensionAttribute8,extensionAttribute9,extensionAttribute10,extensionAttribute11,extensionAttribute12,extensionAttribute13,extensionAttribute14,extensionAttribute15 |
            Export-CSV -Path $YourPathWithFileExtension -Encoding UTF8 -NoTypeInformation -Delimiter ";"

Select-Object has all the properties listed to make the CSV have columns in same order every time. This is important for example possible U-SQL transformations.

 

 

Leave a comment