6

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 Answers 2

9

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 }
Sign up to request clarification or add additional context in comments.

4 Comments

No, I tried that, and got an error -New-MailContact : Cannot bind argument to parameter 'Name' because it is null. At line:1 char:106 + Import-csv c:\FloridaBarTest.csv | Where-Object {$_.ExternalEmailAddress -ne ""} | New-MailContact -Name <<<< $_.Name -FirstName $_.FirstName -LastName $_.FirstName -ExternalEmailAddress $_.ExternalEmailAddress -OrganizationalUnit "FloridaBarContacts" it seems like the csv contents aren't getting passed through the pipeline.
What error(s) are you receiving? Can you update the question with a bit more information?
It might be good to validate the members of the PSObject being passed through the pipeline to make sure you're accessing them. To do this, pipe the results of Import-Csv to Get-Member
Not sure what New-MailContact cmdlet supports on the pipeline so I updated the answer with possibilities.
1

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....}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.