user1390415
user1390415

Reputation: 11

How to skip empty cells in a csv when using PowerShell to import Email Addresses?

I am trying to run the following script to import email addresses in powershell:

Import-CSV "C:\AliasesTest.csv" | foreach-object {
    Set-Mailbox -Display Name $_.Name -EmailAddresses @{add=$_.Alias1,$_.Alias2,$_Alias3}}

It works fine, unless the csv has an empty cell under one of the Alias columns, at which point the following error is produced:

"The address '' is invalid: "" isn't a valid SMTP address..:

How can I construct my script to just ignore empty cells when it comes across them?

Upvotes: 1

Views: 8013

Answers (3)

gpduck
gpduck

Reputation: 381

Check each property (alias) to see if it is empty, and only add the ones with values to the array inside your hash table:

Import-CSV "c:\AliasesTest.csv" | ForEach-Object {
    #Save the CSV row for use in another loop later
    $CSV = $_

    Set-Mailbox -DisplayName $_.Name -EmailAddresses @{add = ("Alias1","Alias2","Alias3" | ForEach-Object { $Csv.$_ } | Where-Object{$_}) }
}

What that craziness does is, create a new hashtable with a key "add" that has a value of a sub expression. The sub expression has an array of property names that you want to check that it iterates over, converting each name to the value of that property, then filters out the empty ones.

Upvotes: 1

zdan
zdan

Reputation: 29450

Filter the aliases to take out the empty ones:

Import-CSV "C:\AliasesTest.csv" | foreach-object {
    $aliases = @($_.Alias1,$_.Alias2,$_Alias3) | where-object{$_};
    Set-Mailbox -Display Name $_.Name -EmailAddresses @{add=$aliases}}

Upvotes: 0

Andy Arismendi
Andy Arismendi

Reputation: 52619

Use a Where-Object filter prior to ForEach-Object like this:

Import-CSV "C:\AliasesTest.csv" | Where-Object {
        $_.Alias1 -and $_.Alias2 -and $_Alias3 
    } | foreach-object { $_ }

If the alias' are empty strings they will be skipped. You don't have to use -and for all of them, if just one value is fine change to use -or.

Upvotes: 0

Related Questions