Find Users by Extension Attribute with Microsoft Graph PowerShell

Learn how to identify users in Microsoft Entra ID by Extension Attribute values using Microsoft Graph PowerShell.

# Validated on Microsoft.Graph PowerShell SDK v2.29.1
$ErrorActionPreference = 'stop'
$requiredScopes = 'User.Read.All'  

$ctx = Get-MgContext
if (-not $ctx -or ($requiredScopes | Where-Object { $ctx.Scopes -notcontains $_ })) {
    Connect-MgGraph -Scopes $requiredScopes -NoWelcome
}
function Get-UsersByExtensionAttribute {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][ValidateRange(1, 15)][int]$AttributeNumber,
        [Parameter(Mandatory)][string]$Value,
        [switch]$StartsWith
    )

    $escaped = $Value -replace "'", "''"
    $attrPath = "onPremisesExtensionAttributes/extensionAttribute$AttributeNumber"

    $filter = if ($StartsWith) {
        "startswith($attrPath,'$escaped')"
    }
    else {
        "$attrPath eq '$escaped'"
    }

    $params = @{
        All              = $true
        PageSize         = 999
        Filter           = $filter
        ConsistencyLevel = 'eventual'
        CountVariable    = 'userCount'
    }

    $users = Get-MgUser @params

    [pscustomobject]@{
        Count = $userCount
        Query = $filter
        Users = $users
    }
}


# Get-UsersByExtensionAttribute -AttributeNumber 1 -Value 'HR-12345'

# Get-UsersByExtensionAttribute -AttributeNumber 3 -Value 'AU-' -StartsWith

# Get-UsersByExtensionAttribute -AttributeNumber 10 -Value 'finance'
Loading...