Yesterday someone asked me to help create a distribution list for everyone reporting to a particular manager (directly or indirectly). Needless to say, that PowerShell makes getting a list of such user accounts a piece of cake!
Here’s the quick script (using AD cmdlets) which I emailed back:
function Get-QADIndirectReport { param ($Identity) # Find all direct reports Get-QADUser -Manager $Identity | ForEach-Object { # Output direct report $_ # Then recursively call this function for all # reports of this report Get-QADIndirectReport -Identity $_ } } # usage example Get-QADIndirectReport 'Dmitry Sotnikov'
Basically, AD cmdlets natively can retrieve all direct reports, and I have created a function which keeps going deeper level-by-level getting everyone reporting indirectly as well.
You can then take this a few steps further. For example, say, you want to get a list of users you could then just copy/paste into Outlook. Simply select the Email property from the user objects and ask PowerShell to put semicolon between the addresses:
# get a list of addresses for an email message (Get-QADIndirectReport 'Dmitry Sotnikov' | Select-Object -ExpandProperty Email) -join '; '
Or you could indeed use the list to populate a group:
# add everyone to a group Get-QADIndirectReport 'Dmitry Sotnikov' | Add-QADGroupMember DmitrysReports
Or you could further restrict the list by City, Department and so on by simply tweaking Get-QADUser parameters in the code above. PowerShell is super-flexible!