Search code examples
powershellazure-active-directoryazure-functions

How to get all users from AAD from an Azure Function by PowerShell?


How to get all users from AAD from an Azure Function by PowerShell? I googled around and try some tutorials, but they are al failed. I hope someone has some solution which works.


Solution

  • Firstly make sure that your Azure Function has the necessary permissions to read user information from AAD. this is imp

    and include the required modules in your PowerShell script:

    # This assumes you have the AzureAD module installed
    Install-Module -Name Az -Force -AllowClobber -Scope CurrentUser
    Install-Module -Name Az -Force -AllowClobber -Scope CurrentUser -AllowPrerelease -MinimumVersion 7.0.0-preview
    
    Import-Module Az

    Now get all the users you need

    # Authenticate to Azure AD
    $tenantId = "<YourTenantId>"
    $clientId = "<YourClientId>"
    $clientSecret = "<YourClientSecret>"
    
    $secpasswd = ConvertTo-SecureString $clientSecret -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($clientId, $secpasswd)
    
    Connect-AzAccount -ServicePrincipal -TenantId $tenantId -ApplicationId $clientId -Credential $credential
    
    # Get all users
    $users = Get-AzADUser -All $true
    
    # Output user information
    $users | Select-Object DisplayName, UserPrincipalName, ObjectId