Create Distribution Group(s) with CSV and PowerShell


To create Distribution Groups in Office 365/Exchange Online I’ve created a script which uses a CSV file for input. The file must be saved as “Unicode, Semicolon separated” (;) and must contain the following fields:

Name Description
Name Name of the Shared Mailbox (this field cannot contain spaces!)
Display Name Full / Display Name
Email Primary email address (this field can contain only one address)
Alias Email alias address(es) – when using more than one: separate them by using a comma (,)
Members Specify the primary email addresses for users who will have access to this mailbox – separate them by using a comma (,)
Hidden Hide or show the Distribution Group in the Global Address List with this field (= required).It can contain only two values: TRUE or FALSE

Make sure that you give the right people (normally the IT department) owner rights for the Distribution Group(s). Because only owners can add members to a group. You need to specify the primary email addresses for the owners in the PowerShell script! Separate the email addresses by using a comma (,).

Script

Here’s the code for the script:

#### Set Variable
Set-Variable -name DGOwners -value admin@wortelltechready.com,user1@wortelltechready.com

#### Create Function Logon to Office365 - Exchange Online
function Logon {
    #### Pop-up a dialog for username and request your password
    $cred = Get-Credential
    #### Import the Local Microsoft Online PowerShell Module Cmdlets and Connect to O365 Online
    Import-Module MSOnline
    Connect-MsolService -Credential $cred
    #### Establish an Remote PowerShell Session to Exchange Online
    $msoExchangeURL = “https://ps.outlook.com/powershell/”
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $cred -Authentication Basic -AllowRedirection
    Import-PSSession $session
                }

#### Create Function Logoff Office365 & Exchange Online
function Logoff {
    #### Remove the Remote PowerShell Session to Exchange Online ----
    Get-PsSession | Remove-PsSession
    #Remove-PsSession $session
                }

############################################################################################################################
############################################################################################################################

#### Logon to Office 365 & Exchange Online
Logon

#### Ask the user for input CSV File
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ofd = New-Object System.Windows.Forms.OpenFileDialog
#$ofd.InitialDirectory = "d:\scripts"
$ofd.ShowHelp=$true
if($ofd.ShowDialog() -eq "OK") { $ofd.FileName }
$File = $ofd.Filename

#### Create Log File + Start Logging
if ($File -ne $Null) {
$Log = $File + ".log"
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path $Log -append
   }

#### Import CSV
Import-csv -Delimiter ";" $File | ForEach {

#### Create DistributionGroup
New-DistributionGroup -Name $_."Name" -Alias $_."Name" -DisplayName $_."Display Name" -PrimarySmtpAddress $_."Email" -Type Distribution

#### Add Aliases
$Aliases = $_.Alias -split ','
if ($Aliases -ne $Null) {
Set-DistributionGroup -Identity $_."Name" -EmailAddresses @{add= $Aliases}
   }

#### Hide or show the DistributionGroup in the Global Address List
if ($_.Hidden) {
[boolean] $StoreBool = [System.Convert]::ToBoolean($_."Hidden")
Set-DistributionGroup -Identity $_."Name" -HiddenFromAddressListsEnabled $StoreBool
    }

#### Add Members
$Name = $_."Name"
$Member = $_.Members -split ","
$Member | Foreach-object {
Add-DistributionGroupMember -Identity $Name -Member $_
   }

#### Set Owners
Set-DistributionGroup $_."Name" -BypassSecurityGroupManagerCheck -ManagedBy $DGOwners

}

#### Stop Logging
Stop-Transcript

#### Logoff
Logoff

Copy and paste the code in notepad (for example) and save it as “CreateDistributionGorup.ps1”. Go through the following steps to use the script.

Steps

Other options you can use with a Distribution Group like Moderation, will have the default values. These can be set separately by using the web interface or with PowerShell.

This is part 4 of a series of posts about some PowerShell scripts I created or used and modified for some Office 365/Exchange Online migrations.

In part 5 of this series I will share a script which can be used to create External Contacts.

An overview of the series can be found here.

Download a sample CVS file from here: CreateDistributionGroup.csv. After the download, rename the file to “CreateDistributionGroup.csv”.

Advertisement

21 thoughts on “Create Distribution Group(s) with CSV and PowerShell

Add yours

  1. Great scrip! I am however not able to run New-DistributionGroup command. Do I need to import some module or something?

    1. Hi Bjorn,
      Yes you need to follow the steps outlined in the post!
      You need to install: “Microsoft Online Services Sign-In Assistant” and “Microsoft Online Services Module for Windows PowerShell”

  2. I did in fact install the sign-in assistant and the PowerShell Module on the ADFS server (requirement for ADFS). But still I don’t get the new-DistributionGroup command. I’m not runnig this on Exchange server though.

  3. I actually keep getting this error: Import-csv : The member “groupname” is already present. This error accures when the script is running: Import-csv -Delimiter “;” $File | ForEach {.
    What am I doning wrong? Do I perhaps need to put the filed names (Name, Display Name, Alias… etc) at the top of the csv file?

  4. Dear Michel, This looks like a very interesting script, but how can i change this script to only add members to several existing DL’s ? and how would the .csv file look like ? I have more then 200 DL’s to populate with lots of members and doing it per DL….hmmm. So lreally looking forward to a script.

    Rgds.
    Toon

    1. Hi Toon,

      You can just comment the part of creating a new Distribution Group out of the script. The CSV will be the same.
      So just put a # before “New-DistributionGroup -Name $_.”Name” -Alias $_.”Name” -DisplayName $_.”Display Name” -PrimarySmtpAddress $_.”Email” -Type Distribution”

  5. Michel, hartelijk bedankt. I’ll try it. I think i will also comment out the Add Alias and Hidden part. One other thing though, for some reason i don’t seem to see all the code lines on screen, on the right side. So can u confirm if these codes are ok:
    (on my screen it ends with -Member $_ } ) see below:

    ####
    Add Members
    $Name = $_.”Name”
    $Member = $_.Members -split “,”
    $Member | Foreach-object {Add-DistributionGroupMember -Identity $Name -Member $_ }

  6. Michel, this powershell causes headaches..;-). I receive:
    Cannot process argument transformation on parameter ‘Member’. Cannot convert va
    lue “” to type “Microsoft.Exchange.Configuration.Tasks.RecipientWithAdUserGroup
    IdParameter`1[Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter]”. Er
    ror: “Parameter values of type Microsoft.Exchange.Configuration.Tasks.Recipient
    WithAdUserGroupIdParameter`1[Microsoft.Exchange.Configuration.Tasks.RecipientId
    Parameter] can’t be empty. Specify a value, and try again.
    Parameter name: identity”
    + CategoryInfo : InvalidData: (:) [Add-DistributionGroupMember],
    ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-Distrib
    utionGroupMember

    I created a test csv in Notepad with 2 “records”, headers called Name and Members separated by ; , column members has several e-mail addresses separated by , and saved as csv and unicode.
    My code is only:

    Import-csv -Delimiter “;” c:\New\DList.csv | ForEach {
    $Name = $_.”Name”
    $Member = $_.Members -split “,”
    $Member | Foreach-object { Add-DistributionGroupMember -Identity $Name -Member $_ }
    }

  7. Michel, never mind. I found the error. The $Member =$_Members -split “,” should have been $Member=$_Member -split “,”
    as the column name is Member, and not Members with the s like yours.

    Thx

  8. Hi MIchel, What an absolutely brilliant script. I have not only learned more regarding logging but in general it is a really nice script. have definitely inspired me to write “nicer” scripts in the future. Oh and i love the dialog box for prompting for CSV file 🙂

  9. i want to export all the gropus and their owners to a csv file, how do i go about it

    1. Hi Joseph,

      I normally use the following PowerShell code to export detail information of DistGroups including owners (ManagedBy)…hope this helps?

      # Variables
      $DGCSV=”DistGroups.csv”

      ## Export Filtered Group Info
      Get-DistributionGroup -ResultSize Unlimited | Select `
      Name, `
      @{Name=’AcceptMessagesOnlyFrom’;Expression={[string]::join(“,”, ($_.AcceptMessagesOnlyFrom))}}, `
      @{Name=’AcceptMessagesOnlyFromDLMembers’;Expression={[string]::join(“,”, ($_.AcceptMessagesOnlyFromDLMembers))}}, `
      @{Name=’AcceptMessagesOnlyFromSendersOrMembers’;Expression={[string]::join(“,”, ($_.AcceptMessagesOnlyFromSendersOrMembers))}}, `
      Alias, `
      @{Name=’BypassModerationFromSendersOrMembers’;Expression={[string]::join(“,”, ($_.BypassModerationFromSendersOrMembers))}}, `
      BypassNestedModerationEnabled, `
      DisplayName, `
      @{Name=’EmailAddresses’;Expression={[string]::join(“,”, ($_.EmailAddresses -notlike “*.onmicrosoft.com” -notlike “*.microsoftonline.com” -notlike “x500:*” -notlike “x400:*”))}}, `
      @{Expression={$_.GrantSendOnBehalfTo};Label=”GrantSendOnBehalfTo”;}, `
      GroupType, `
      HiddenFromAddressListsEnabled, `
      Identity, `
      MailTip, `
      @{Name=’MailTipTranslations’;Expression={[string]::join(“,”, ($_.MailTipTranslations))}}, `
      @{label=”ManagedBy”;expression={[string]::join(“,”,($_.ManagedBy | ForEach {
      $Recipient=$_.tostring().split(“/”)[-1]
      (Get-Recipient $Recipient).PrimarySMTPAddress
      }
      ))}}, `
      MaxReceiveSize, `
      MaxSendSize, `
      #@{label=”Members”;expression={[string]::join(“,”,((Get-DistributionGroupMember -ResultSize Unlimited -Identity $_.Name).PrimarySMTPAddress))}}, `
      MemberDepartRestriction, `
      MemberJoinRestriction, `
      @{label=”ModeratedBy”;expression={[string]::join(“,”,($_.ManagedBy | ForEach {
      $Recipient=$_.tostring().split(“/”)[-1]
      (Get-Recipient $Recipient).PrimarySMTPAddress
      }
      ))}}, `
      ModerationEnabled, `
      PrimarySmtpAddress, `
      RecipientType, `
      RecipientTypeDetails, `
      @{Expression={$_.RejectMessagesFrom};Label=”RejectMessagesFrom”;}, `
      @{Expression={$_.RejectMessagesFromDLMembers};Label=”RejectMessagesFromDLMembers”;}, `
      @{Expression={$_.RejectMessagesFromSendersOrMembers};Label=”RejectMessagesFromSendersOrMembers”;}, `
      ReportToManagerEnabled, `
      ReportToOriginatorEnabled, `
      RequireSenderAuthenticationEnabled, `
      SendModerationNotifications, `
      SendOofMessageToOriginatorEnabled, `
      SimpleDisplayName, `
      IsDirSynced `
      | Export-CSV $DGCSV -Delimiter “;” -NoTypeInformation -Encoding UTF8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: