5
votes

I am trying to write a powershell script for Exchange Management Shell, importing a list of contacts from a csv file into a distribution group.

I start out with

Import-csv C:\filename.csv | forEach-Object {New-MailContact .......}

This works well, except that some entries in my csv file have a blank email address, and the create teh new contact craps out because ExternalEmailAddress is blank. So, I tried:

Import-csv C:\filename.csv | ForEach-Object { Where-Object {$_.ExternalEmailAddress -ne "" } | New-MailContact -Name $_.Name -ExternalEmailAddress $_.ExternalEmailAddress....}

But that didn't seem to work - it didn't filter out the entries with blank email addresses.

What am I doing wrong?

2

2 Answers

9
votes

I think you might want to use Where-Object prior to ForEach-Object because it will filter the objects passed along the pipeline.

Depending on what the New-MailContact cmdlet supports you might be able to pipe the results directly into it or you may have to pass them one by one.

All at once (NOT using ForEach-Object):

Import-csv C:\filename.csv | Where-Object {$_.ExternalEmailAddress -ne "" } | New-MailContact -Name $_.Name -ExternalEmailAddress $_.ExternalEmailAddress }

One by one (by using ForEach-Object):

Import-csv C:\filename.csv | Where-Object {$_.ExternalEmailAddress -ne "" } | ForEach-Object { New-MailContact -Name $_.Name -ExternalEmailAddress $_.ExternalEmailAddress }
1
votes

Could be there's actually a space or some other white space character there, and they're not actully null. Maybe something like this:

 Import-csv C:\filename.csv | Where-Object {$_.ExternalEmailAddress -match "^\S+$" } | New-MailContact -Name $_.Name -ExternalEmailAddress $_.ExternalEmailAddress....}