How do I ignore empty cells in a csv when using PowerShell to import email addresses?

advertisements

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?


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.