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:tempUsers.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
New contributor
Asthika Welikala is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.