The approach you're suggesting is on the right track, but there are some nuances to take into consideration.
Here's a guide to achieve this:
Connect to Azure AD:
Connect-AzureAD
Write and Execute the Query:
The Get-ADUser cmdlet is specific to on-prem AD so you can't use this with Azure. Instead, you'll use Get-AzureADUser.
unfortunately, this cmdlet doesn't directly support the complex filter like you've mentioned, so you'll fetch all users and filter them in PowerShell.
$rule = {
$_.AccountEnabled -eq $true -and $_.Department -like "1234*"
}
# Fetch all Azure AD users and filter based on the rule
$filteredUsers = Get-AzureADUser -All $true | Where-Object $rule
# Select the necessary properties and export to a CSV
$filteredUsers | Select-Object DisplayName,UserPrincipalName,Mail,Department,JobTitle,OfficeLocation | Export-Csv C:\temp\output.csv -NoTypeInformation
Note: Ensure to adjust the attributes to match those available in Azure . The ones you've mentioned like SamAccountName, EmailAddress, etc. are not directly available as-is in Azure AD, but they have their counterparts. For example, UserPrincipalName is similar to SamAccountName in many use-cases, and Mail is the email address.
Once you validate the users exported in the CSV match your expectations, you can confidently apply the rule to the dynamic group in Azure AD.
If you found this helpful kindly mark it as the answer and consider following! Thank you