Search code examples
azurepowershell

Connect to Azure AD with service principal to get a listing of users and info


I'm trying to connect to Azure AD and get a listing of accounts that match a specific company and get a file with the account info. The script works if I use an interactive login, but I need to automate this with the service principal login. I get an error at get-azureaduser in this script - what am I doing wrong?

# Connect to Azure AD
$tenantId = "xxxxxxx"
$clientId = "xxxxxxx"
$clientSecret = "xxxxxxxxx"

import-module az

$secureClientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential($clientId,    $secureClientSecret)
 
Connect-Azaccount -ServicePrincipal -TenantId $tenantId -Credential $credential

# Define the company name to filter by
$companyName = "some company"

# Get users from Azure AD, filter by company name and job title, and select required properties
$users = Get-AzureADUser -All $true | Where-Object {
    $_.CompanyName -eq $companyName -and $_.JobTitle -ne $null
    } | Select-Object DisplayName, JobTitle, Mail, Department

# Export the filtered users to a CSV file
$users | Export-Csv -Path "c:\temp\Users.csv" -NoTypeInformation

I tried adding

$currentAzureContext = Get-AzContext
$tenantId = $currentAzureContext.Tenant.Id
$accountId = $currentAzureContext.Account.Id
Connect-AzureAD -TenantId $tenantId -AccountId $accountId

but that also brings up a login prompt


Solution

  • Note that: Azure AD PowerShell module supports service principal authentication or gives no prompt only when CertificateThumbprint and ApplicationId are passed. Refer this MsDoc

    Hence make use of Connect-AzureAD and modify the script like below:

    # Define your tenant ID, application ID, and certificate thumbprint
    $tenantId = "TenantID"
    $applicationId = "APPID"
    $certThumbprint = "CertTumbPrint"
    
    # Connect to Azure AD using the certificate
    Connect-AzureAD -CertificateThumbprint $certThumbprint -ApplicationId $applicationId -TenantId $tenantId
    
    # Define the company name to filter by
    $companyName = "ruk"
    
    $users = Get-AzureADUser -All $true | Where-Object {
        $_.CompanyName -eq $companyName -and $_.JobTitle -ne $null
        } | Select-Object DisplayName, JobTitle, Mail, Department
    
    # Export the filtered users to a CSV file
    $users | Export-Csv -Path "C:\Users\v-rukmini\Downloads\rukcsvaad.csv" -NoTypeInformation
    

    enter image description here

    enter image description here

    Make sure to upload certificate in the Microsoft Entra ID application:

    enter image description here

    • The .cer certificate must be uploaded to the Microsoft Entra ID application
    • The .pfx certificate must be present in the local machine where you are executing the code.
    • Otherwise, make use of Connect-Azaccount -ServicePrincipal and use Get-AzADUser