Search code examples
powershellexchange-server

Powershell to loop through .CSV to create Distribution List?


I want to modify the below PowerShell cmdlet to create bulk DLs with its members and its aliases.

Using the two cmdlets below:

I've managed to create just one DL when executed with the snippets below:

$paramNewDistributionGroup = @{
   Name                             = $_.DisplayName
   Alias                            = $_.Alias
   PrimarySmtpAddress               = $_.PrimarySmtpAddress
   DisplayName                      = $_.DisplayName
   RequireSenderAuthenticationEnabled = $False
   Members                          = $_.Members
}

New-DistributionGroup @paramNewDistributionGroup

$paramSetDistributionGroup = @{
   Identity       = $_.Alias
   EmailAddresses = @{ Add = $_.SecondarySMTPAddress }
}

Set-DistributionGroup @paramSetDistributionGroup

How to modify the above script so it takes the .CSV file which looks like the below:

enter image description here

Using the suggested code from @mklement below, it throws an error due to the multi-value entries on the below columns:

SecondarySMTPAddress column:

Write-ErrorMessage : Cannot process argument transformation on parameter 'EmailAddresses'. Cannot convert value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" to type "Microsoft.Exchange.Data.ProxyAddressCollection". Error: "The address 'Execs@domain.com; boss@domain.com ' is invalid: The address 'Execs@domain.com; boss@domain.com' isn't a valid Unified Messaging address, so a prefix must be specified."

Members column:

Write-ErrorMessage : Ex94914C|Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException|Couldn't find object " Cella Cat; Maria Aya; Heni Amor; Dio O'meara". Please make sure that it was spelled correctly or specify a different object.


Solution

  • Assuming this is on-prem Exchange?

    $DLs = Import-Csv -Path <filepath>
    $DLS | % {
        $paramNewDistributionGroup = @{
           Name                             = $_.DisplayName
           Alias                            = $_.Alias
           PrimarySmtpAddress               = $_.PrimarySmtpAddress
           DisplayName                      = $_.DisplayName
           RequireSenderAuthenticationEnabled = $False
           Members                          = $_.Members
        }
    
        New-DistributionGroup @paramNewDistributionGroup
    
        $paramSetDistributionGroup = @{
           Identity       = $_.Alias
           EmailAddresses = @{ Add = $_.SecondarySMTPAddress }
        }
    
        Set-DistributionGroup @paramSetDistributionGroup
    }
    

    I'm also going to assume the members within your CSV file match one of these AD attributes:

    • Name
    • Alias
    • Distinguished name (DN)
    • Canonical DN
    • Email address
    • GUID