Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create mail enabled security group based on O365 Unified group
## Option 1 - This can be used to be prompted for credentials
$UserCredential = Get-Credential
## Option 2 - If you really want to automate the script, you will
## want to hard code the credentials to log into Azure AD.
# $User = "<ADMIN USER>"
# $PWord = ConvertTo-SecureString -String "<PASSWORD>" -AsPlainText -Force
# $UserCredential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
## Create the session to Exchange Online
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
## Import the Exchange Online commands
Import-PSSession $Session
## Requires the Azure AD 2.0 cmdlets
## Install-Module -Name AzureAD
Connect-AzureAD -credential $UserCredential
## Set the names for the groups
## Old Group = Office 365 Unified Group
## New Group = The new Mail enabled security group that will be created.
$oldGroupName = "Sales Group"
$newGroupName = "My Group"
## Get references to old and new group.
## New group may be null if it hasn't been created yet.
$oldGroup = Get-AzureADGroup -SearchString $oldGroupName
$newGroup = Get-AzureADGroup -SearchString $newGroupName
if($newGroup -eq $null)
{
## Update the managedby and PrimarySmtpAddress addresses
## Managed by = owner of group
## these can be changed later in the Exchange Online Admin portal
New-DistributionGroup -Name $newGroupName -Type "Security" -ManagedBy "asaxton@guyinacube.com" -PrimarySmtpAddress "mygroup@guyinacube.com"
Write-Output "New group created!"
## Get reference to new group
$newGroup = Get-AzureADGroup -SearchString $newGroupName
}
else
{
Write-Output "New group already exists!"
}
$oldGroupMembers = Get-AzureADGroupMember -ObjectId $oldGroup.ObjectId -All $true
$newGroupMembers = Get-AzureADGroupMember -ObjectId $newGroup.ObjectId -All $true
## Add old members to new group
## Check to make sure the member doesn't already exist.
Foreach ($member in $oldGroupMembers)
{
if($newGroupMembers -notcontains $member)
{
Add-DistributionGroupMember -Identity $newGroupName -Member $member.UserPrincipalName
$message = "New group does not contain member - "
$message += $member.UserPrincipalName
Write-Output $message
}
else
{
$message = "New group contains member - "
$message += $member.UserPrincipalName
Write-Output $message
}
}
## list out members of the new group
Get-AzureADGroupMember -ObjectId $newGroup.ObjectId -All $true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment