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?
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 }
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....}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With