Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell scripting using where-object

Tags:

powershell

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?

like image 544
Ken Ray Avatar asked Feb 09 '11 15:02

Ken Ray


2 Answers

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 }
like image 55
Scott Saad Avatar answered Sep 28 '22 22:09

Scott Saad


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....}
like image 43
mjolinor Avatar answered Sep 28 '22 22:09

mjolinor