PowerShell for creating bulk Distribution group

Meghashree Vijaya 1 Reputation point
2022-11-02T10:21:22.527+00:00

Powershell script to bulk-create distribution groups by importing the details from a CSV file with all the attributes. I have created a script to export all the DLs with all the required attributes and trying to reverse it for creating new DLs

CSV file export path

$Csvfile = "C:\Users\Meghashree.Vijaya\Documents\ExportDGs.csv"

Get all distribution groups

$Groups = Get-DistributionGroup -ResultSize Unlimited

Loop through distribution groups

$Groups | ForEach-Object {

$GroupDN = $.DistinguishedName
$DisplayName = $
.DisplayName
$PrimarySmtpAddress = $.PrimarySmtpAddress
$SecondarySmtpAddress = $
.EmailAddresses | Where-Object {$_ -clike "smtp*"} | ForEach-Object {$_ -replace "smtp:",""}
$GroupType = $.GroupType
$RecipientType = $
.RecipientType
$Members = Get-DistributionGroupMember $GroupDN -ResultSize Unlimited
$ManagedBy = $.ManagedBy
$Alias = $
.Alias
$HiddenFromAddressListsEnabled = $.HiddenFromAddressListsEnabled
$MemberJoinRestriction = $
.MemberJoinRestriction
$MemberDepartRestriction = $.MemberDepartRestriction
$RequireSenderAuthenticationEnabled = $
.RequireSenderAuthenticationEnabled
$ModerationEnabled = $.ModerationEnabled
$ModeratedBy = $
.ModeratedBy
$BypassModerationFromSendersOrMembers = $.BypassModerationFromSendersOrMembers
$SendModerationNotifications = $
.SendModerationNotifications
$AcceptMessagesOnlyFrom = $.AcceptMessagesOnlyFrom
$GrantSendOnBehalfTo = $
.GrantSendOnBehalfTo
$MailTip = $_.MailTip
$Notes = (Get-Group $GroupDN)

Create objects

[PSCustomObject]@{  
    DisplayName                          = $DisplayName  
    PrimarySmtpAddress                   = $PrimarySmtpAddress  
    SecondaryStmpAddress                 = ($SecondarySmtpAddress -join ',')  
    Alias                                = $Alias  
    GroupType                            = $GroupType  
    RecipientType                        = $RecipientType  
    Members                              = ($Members.Name -join ',')  
    MembersPrimarySmtpAddress            = ($Members.PrimarySmtpAddress -join ',')  
    ManagedBy                            = ($ManagedBy -join ',')  
    HiddenFromAddressListsEnabled        = $HiddenFromAddressListsEnabled  
    MemberJoinRestriction                = $MemberJoinRestriction  
    MemberDepartRestriction              = $MemberDepartRestriction  
    RequireSenderAuthenticationEnabled   = $RequireSenderAuthenticationEnabled  
    ModerationEnabled                    = $ModerationEnabled  
    ModeratedBy                          = ($ModeratedBy -join ',')  
    BypassModerationFromSendersOrMembers = ($BypassModerationFromSendersOrMembers -join ',')  
    SendModerationNotifications          = $SendModerationNotifications  
    AcceptMessagesOnlyFrom               = ($AcceptMessagesOnlyFrom -join ',')  
    GrantSendOnBehalfTo                  = ($GrantSendOnBehalfTo -join ',')  
    MailTip                              = $MailTip  
    Notes                                = $Notes.Notes  
}  

Export report to CSV file

} | Sort-Object DisplayName | Export-CSV -Path $Csvfile -NoTypeInformation -Encoding UTF8 #-Delimiter ";"

Windows for business Windows Server User experience PowerShell
{count} votes

5 answers

Sort by: Most helpful
  1. Meghashree Vijaya 1 Reputation point
    2022-11-03T04:58:54.537+00:00

    The code I have posted is for exporting all the DLs. I am looking for a code to import all the data I got using the export code and create DLs. Hope you can help me with this

    0 comments No comments

  2. Limitless Technology 44,746 Reputation points
    2022-11-03T08:39:25.81+00:00

    Hello there,

    I am not sure what is the question here. Do you get any error message while running the script?

    To confirm if the distribution lists have been created , run the PowerShell cmdlet Get-Distributiongroup, this cmdlet returns a summary list of all distribution list and mail-enabled security groups in your organization.

    --------------------------------------------------------------------------------------------------------------------------------------------

    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments

  3. Meghashree Vijaya 1 Reputation point
    2022-11-03T13:52:48.083+00:00

    CSV file import path

    $DLlist = Import-CSV C:\Users\Meghashree.Vijaya\Documents\DL.csv

    Loop through each row

    ForEach ($DL in $DLlist)
    {
    New-DistributionGroup -Name $DL.DisplayName -Alias $DL.Alias -ManagedBy $DL.ManagedBy.Split(",") -PrimarySmtpAddress $DL.PrimarySmtpAddress

    Set-DistributionGroup -Identity Name -HiddenGroupMembershipEnabled $DL.HiddenFromAddressListsEnabled -RequireSenderAuthenticationEnabled $DL.RequireSenderAuthenticationEnabled = [System.Convert]::ToBoolean($DL.RequireSenderAuthenticationEnabled) -MemberJoinRestriction "ApprovalRequired" -MemberDepartRestriction "Open" -AcceptMessagesOnlyFrom $DL.AcceptMessagesOnlyFrom -ModerationEnabled $DL.ModerationEnabled
    -ModeratedBy $DL.ModeratedBy.Split(",") -BypassModerationFromSendersOrMembers $DL.BypassModerationFromSendersOrMembers -SendModerationNotifications $DL.SendModerationNotifications
    -GrantSendOnBehalfTo = $DL.GrantSendOnBehalfTo.Split(",") -MailTip $DL.MailTip -Notes $DL.Notes

    Add-DistributionGroupMember -Identity -Member $DL.MembersPrimarySmtpAddress.Split(",")
    }

    $VarName.ToBoolean($_.value)

    Get-DistributionGroup "DL-Cloud Testing" | fl

    To test further

    Cannot process argument transformation on parameter 'RequireSenderAuthenticationEnabled'. Cannot convert value
    "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True,
    $False, 1 or 0.

    • CategoryInfo : InvalidData: (:) [Set-DistributionGroup], ParameterBindin...mationException
    • FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-DistributionGroup
    • PSComputerName : outlook.office365.com

    -ModeratedBy : The term '-ModeratedBy' is not recognized as the name of a cmdlet, function, script file, or operable
    program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:10 char:1

    • -ModeratedBy $DL.ModeratedBy.Split(",") -BypassModerationFromSendersO ...
    • ~~~~~~~~~~~~
    • CategoryInfo : ObjectNotFound: (-ModeratedBy:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException

    -GrantSendOnBehalfTo : The term '-GrantSendOnBehalfTo' is not recognized as the name of a cmdlet, function, script
    file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
    and try again.
    At line:11 char:1

    • -GrantSendOnBehalfTo = $DL.GrantSendOnBehalfTo.Split(",") -MailTip $D ...
    • ~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : ObjectNotFound: (-GrantSendOnBehalfTo:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException

    Cannot process argument transformation on parameter 'Member'. Cannot convert the "System.Collections.ArrayList" value
    of type "System.Collections.ArrayList" to type "Microsoft.Exchange.Configuration.Tasks.RecipientWithAdUserGroupIdParame
    ter`1[Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter]".

    • CategoryInfo : InvalidData: (:) [Add-DistributionGroupMember], ParameterBindin...mationException
    • FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-DistributionGroupMember
    • PSComputerName : outlook.office365.com
    0 comments No comments

  4. Rich Matheisen 47,901 Reputation points
    2022-11-03T18:19:44.94+00:00

    Try this:

    # function converts text true/false to boolean  
    function TF{  
        param([string]$state)  
        if      ($state -eq 'true')     {$true}  
        elseif  ($state -eq 'false')    {$false}  
        else                            {'Unknown'}  
    }  
      
    #Loop through each row  
    Import-CSV C:\Users\Meghashree.Vijaya\Documents\DL.csv |  
        ForEach-Object{  
            Try{  
                $n = New-DistributionGroup -Name $_.DisplayName -Alias $_.Alias -ManagedBy $_.ManagedBy.Split(",") -PrimarySmtpAddress $_.PrimarySmtpAddress -ErrorAction STOP  
      
                $props = @{  
                    Name = $_.DisplayName  
                    HiddenGroupMembershipEnabled            = TF $_.HiddenFromAddressListsEnabled  
                    RequireSenderAuthenticationEnabled      = TF $_.RequireSenderAuthenticationEnabled  
                    MemberJoinRestriction                   = "ApprovalRequired"  
                    MemberDepartRestriction                 = "Open"  
                    AcceptMessagesOnlyFrom                  = $_.AcceptMessagesOnlyFrom -split ','                  # multi-valued property  
                    ModerationEnabled                       = TF $_.ModerationEnabled  
                    BypassModerationFromSendersOrMembers    = $_.BypassModerationFromSendersOrMembers -split ","    # multi-valued property  
                    SendModerationNotifications             = $_.SendModerationNotifications  
                    GrantSendOnBehalfTo                     = $_.GrantSendOnBehalfTo -split ','                     # multi-valued property  
                    MailTip                                 = $_.MailTip  
                    #   Notes = $_.Notes       # there is no Notes property  
                }  
      
                $n | Set-DistributionGroup @props -ErrorAction STOP  
                Add-DistributionGroupMember -Identity -Member $_.MembersPrimarySmtpAddress.Split(",") -ErrorAction STOP  
            }  
            Catch{  
                $_  
            }  
        }  
    
    0 comments No comments

  5. Meghashree Vijaya 1 Reputation point
    2022-11-10T08:52:57.57+00:00

    It is showing the message below

    cmdlet Set-DistributionGroup at command pipeline position 1
    Supply values for the following parameters:
    Identity:


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.