Forum Discussion
Dynamic Office 365 groups
- Aug 16, 2016
It is available with Azure AD premium subscription.
I am not a great coder or scripter but I was able to come up with the following solution.
I created a powershell script that iterates through the AD structure automatically adding users to the Office 365 group based off of job titles. I have this scheduled in task manager on our DC that hosts the AAD Connect software to run once a day adding and removing users from the Office 365 Group. The criteria can be changed to look at any field in the AD structure.
#Sets up the powershell environment retrieving an encrypted password from a text file decrypting it and storing the password in the $O365credential variable
$pwdloc=Join-Path (Split-Path $profile) creds.txt
$O365password = gc $pwdloc
$o365password = ConvertTo-SecureString $O365password -Force
import-module msonline
$O365username = '<office 365 username>'
$O365credential = New-Object System.Management.Automation.PSCredential -ArgumentList $O365username,$O365password
$sessionProxy = New-PSSessionOption -ProxyAccessType IEConfig -ea stop
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $O365credential -Authentication Basic -AllowRedirection -ea stop
Import-PSSession $Session -AllowClobber -DisableNameChecking -ea stop
Connect-MsolService -Credential $O365credential
Import-Module ActiveDirectory
# Check Users for keywords in title and add or remove users from the Office 365 Group
#Sets email address of all users who meet the criteria
$Users = (get-aduser -SearchBase "AD structure search base" -filter {(title -like "*Sales*")} -Properties sAMAccountName,Title,mail | select-object mail).mail
#Grabs members of the Office 365 Group
$UsersUnifiedGroup = (get-unifiedgrouplinks -identity <Office 365 Group> -linktype members | select-object primarysmtpaddress).primarysmtpaddress
#Loops through object to return email addresses needing to be added as a variable
$AddToUsersUnifiedGroup = $Users | where{$UsersUnifiedGroup -notcontains $_}
#Loops through object to return email addresses needing to be removed as a variable
$RemoveFromUsersUnifiedGroup = $UsersUnifiedGroup | where{$Users -notcontains $_}
#Loop to add users to the Office 365 Group
foreach($AddToUsersUnifiedGroupEmail in $AddToUsersUnifiedGroup) {add-unifiedgrouplinks -identity <Office 365 Group> -links $AddToUsersUnifiedGroupEmail -linktype members -confirm:$false}
#Loop to remove users from the Office 365 Group
foreach($RemoveFromUsersUnifiedGroupEmail in $RemoveFromUsersUnifiedGroup) {remove-unifiedgrouplinks -identity <Office 365 Group> -links $RemoveFromUsersUnifiedGroupEmail -linktype members -confirm:$false}