I had a request come to me today for an AD group that will always contain all of the users in a particular OU. If you have come across my little place on the internet before, you are likely familiar that I do a lot of work with AD FS. Keeping that in mind, I wanted to make sure only users that were synced with Azure AD/O365 from this OU were added to the group. Additionally, if that user were no longer synced with Azure AD/O365 I wanted to remove them from the group to keep it tidy. And thus I came up with the following script that I have run every hour:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
<# .SYNOPSIS This script will: -Determine if user is synced with O365 -Determine if user is a member of distro -Add user to distro if synced with O365 -Remove user from distro if not synced with O365 .PREREQUISITES For this script to work: -AD access to edit user and group objects in locations specified by variables .NOTES Author: Scott Shelton Date: 04/12/2018 Version: 1.0 .CHANGELOG #> ########### #Variables# ########### #Domain Controller $strDomainController = "DC.domain.local" #Sync Group Distinguished Name $strSyncGroupDN = "CN=SyncGroupName,OU=OUNAME,DC=DOMAIN,DC=LOCAL" #Distribution Group Distinguished Name $strDistroDN = "CN=GroupName,OU=OUNAME,DC=DOMAIN,DC=LOCAL" #User OU $strSearchBaseDN = "OU=SubOUName,OU=OUNAME,DC=DOMAIN,DC=LOCAL" #Array of Users $arrUsers = Get-ADUser -Server $strDomainController -Filter * -SearchBase $strSearchBaseDN -Properties memberof ########### #Functions# ########### #Determine if user is synced with O365 function SyncedWithO365($User) { if($User.memberof -contains $strSyncGroupDN) { return $true } return $false } #Determine if user is member of Distribution Group function MemberOfDistro($User) { if($User.memberof -contains $strDistroDN) { return $true } return $false } ################ #Let's Do Stuff# ################ foreach($tmpUser in $arrUsers) { #Determine if user is synced with O365 $tfSyncedWithO365 = SyncedWithO365 -User $tmpUser #Determine if user is member of Distribution Group $tfMemberOfDistro = MemberOfDistro -User $tmpUser #If user is synced with O365 if($tfSyncedWithO365 -eq $true) { #Add User to Distribution Group Add-ADGroupMember -Server $strDomainController -Identity $strDistroDN -Members $tmpUser } #If user is NOT synced with O365 elseif($tfSyncedWithO365 -eq $false) { #If user is a member of the Distribution Group if($tfMemberOfDistro -eq $true) { #Remove the user from Distribution Group Remove-ADGroupMember -Server $strDomainController -Identity $strDistroDN -Members $tmpUser -Confirm:$false } } } |