Add users with the same Manager and mail domain to a DL, ( No dynamic ), with PS

Iron Contributor

Hello Community,


Recently I got a special request. A script that adds new joiners, ( or users that changed department/office ), that are all under the same Manager to a Distribution List. The standard will be think about a dynamic DL, but in that specific environment wasn't an option, ( Manager isn't eligible and not all users with the same manager have other atrtibutes in common. Custom attributes, due the process of users creation, wasn't an option as well ). On the other hand, in this environment there're many users with different domains and they wanted only one specific domain users.


So, I created a script that connects to MgGraph and Exchange Online, ( you can modify it to connect to Exchange OnPrem for hybrid scenarios ), that collects all users reporting to the required manager, ( you'll need the Manager ObjectId ), filters the list for users with the desired domain and add them to the DL if they're not already members.


NOTE: This is a personal script, tested by me and working in my environment. Please test it and adapt it as per your requirements. 



# Connect to Microsoft Graph
Write-host "Connecting to Microsoft Graph..." -ForegroundColor "Yellow"

Connect-MgGraph -Scopes "User.Read.All","Directory.Read.All"

# Connect to Exchange
Write-host "Connecting to Exchange..." -ForegroundColor "Yellow"


# Get Manager's Direct Reports
Write-host "Getting users with Manager Name as Manager..." -ForeGroundColor 'Yellow'

$DirectReport=Get-MgUserDirectReport -UserId a8691c6b-User-Object-ID-fc1503f573e1 | select Id

# Filter Direct Reports for users only

Write-host "Filtering accounts..." -ForegroundColor 'Yellow'

foreach ($Id in $DirectReport){
    $Users=Get-MgUser -UserId $Id.Id | Where-Object {$_.Mail -like '*'} | Select-Object Mail

    # Check for Group Membership

    Write-host "Checking Group Membership..." -ForegroundColor 'Yellow'

    $DL=Get-DistributionGroupMember -Identity $GroupName | Select PrimarySmtpAddress

    foreach ($Mail in $Users){
    if ($DL.PrimarySmtpAddress -notcontains $Mail.Mail) {
    #Add Users to the DL
    Write-Host "Adding users to the DL..." -ForegroundColor "Yellow"

    Add-DistributionGroupMember -Identity $GroupName -Member $Mail.Mail -BypassSecurityGroupManagerCheck}
    Write-host "Script completed successfully" -ForegroundColor "Green"


0 Replies