A dynamic group is needed that includes all members under a Senior VP in Azure Active Directory. The approach involves listing all managers under the SVP and using the user.manager
attribute to construct the dynamic query. The resulting query script output appears as follows:
(user.manager -eq "managerobjectId") -or (user.manager -eq "managerobjectId") -or ...
Questions:
- Is this syntax and query valid for an Azure dynamic group?
- Is there an alternative approach that doesn't require custom attributes, especially considering that the query would need to be reconstructed if a manager under the SVP leaves the organization?
Below is the PowerShell script used for this process:
# Load Microsoft Graph
#Import-Module Microsoft.Graph
Connect-MgGraph -Scopes "User.Read.All", "Directory.Read.All"
# Set your SVP's UPN or Object ID
$svpIdOrUpn = "******@domain.com"
# Recursive function to get all users under a given manager
function Get-AllReportees {
param (
[string]$ManagerId
)
$allReportees = @()
try {
$directReports = Get-MgUserDirectReport -UserId $ManagerId -All
} catch {
Write-Warning "Failed to get direct reports for $ManagerId $_"
return
}
foreach ($user in $directReports) {
$allReportees += $user
$allReportees += Get-AllReportees -ManagerId $user.Id
}
return $allReportees
}
# Step 1: Get SVP object
$svp = Get-MgUser -UserId $svpIdOrUpn
if (-not $svp) {
Write-Host "❌ Could not find user with ID or UPN: $svpIdOrUpn" -ForegroundColor Red
return
}
# Step 2: Recursively get all reportees
Write-Host "`n🔍 Fetching reportees under SVP: $($svp.DisplayName)`n"
$reportees = Get-AllReportees -ManagerId $svp.Id
Write-Host "✅ Found $($reportees.Count) users under SVP.`n"
# Step 3 & 4: Use all reportees as managers, plus the SVP
$managerIds = $reportees | Select-Object -ExpandProperty Id
$managerIds += $svp.Id
$managerIds = $managerIds | Sort-Object -Unique
# Step 5: Build the dynamic group rule
$ruleClauses = $managerIds | ForEach-Object { "(user.manager -eq `"$($_)`")" }
$dynamicRule = $ruleClauses -join " -or "
# Output result
Write-Host "`n📋 Generated Dynamic Group Rule:`n" -ForegroundColor Cyan
Write-Host $dynamicRule
# Optional: Save to file
$dynamicRule | Out-File -FilePath "c:\temp\SVP_DynamicRule_Final.txt" -Append -Encoding UTF8