Script Repository


Create mail-enabled group in Exchange Online based on AD group

May 14, 2018
1986

The script creates a mail-enabled group in Exchange Online based on an existing Active Directory group and sets the email address for both groups. Group members will be sycnronized by AD Sync.

Parameters:

  • $domainName - specifies the domain name (e.g. example.com) that will be used in the $primarySmtpAddress variable;
  • $primarySmtpAddress - specifies the e-mail adress that will be set for the groups.
Edit Remove
PowerShell
$domainName = "domain.com" # TODO: modify me
$primarySmtpAddress = "%name%@$domainName" # TODO: modify me

# Get group type
$groupType = $Context.TargetObject.Get("groupType")
if ($groupType -band [Softerra.Adaxes.Interop.Adsi.ADS_GROUP_TYPE_ENUM]::ADS_GROUP_TYPE_SECURITY_ENABLED)
{
    $type = "Security"
}
else
{
    $type = "Distribution"
}

try
{
    # Connect to Exchange Online
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Context.GetOffice365Credential() -Authentication Basic -AllowRedirection
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName "New-DistributionGroup"
    
    # Create new group
    try
    {
        New-DistributionGroup -Name "%name%" -PrimarySmtpAddress $primarySmtpAddress -Type $type -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred when creating group in Exchange online. Error: " + $_.Exception.Message, "Warning")
        return
    }
    
    # Update AD group mail
    $Context.TargetObject.Put("mail", $primarySmtpAddress)
    $Context.TargetObject.SetInfo()
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession $session }
}


Comments ( 0 )
No results found.
Leave a comment