We help IT Professionals succeed at work.

How to deal with an empty string when making a mail contact using powershell

ndalmolin_13
ndalmolin_13 used Ask the Experts™
on
Greetings Powershell Experts –

I have a csv file from which I would like to make mail contacts.  The csv file’s data has been displayed below:

Firstname      Lastname      emailaddress
Bob      Smith      bsmith@yahoo.com
Nancy      Jones      nancy.jones@gmail.com
Ted       Collins      tedcollins123@msn.com
Jill       Parker      jillp@hotmail.com
            yourock@hotmail.com
            abf13134@infomagic.com


I have written the following Powershell code that creates the mail contact as expected as long as a firstname and lastname exist in the csv file.  However when an entry in the file that does not have a firstname and/or lastname is encountered, I get an error and a contact is not made.

$Contacts = Import-Csv c:\work\emaillist.csv

Foreach ($contact in $Contacts)
{
$name = $contact.firstname + "" + $contact.lastname
$email = $contact.emailaddress

New-MailContact -Name $name -FirstName $contact.firstname -LastName $contact.lastname -ExternalEmailAddress $email -OrganizationalUnit "summitlan.states/test"

}

For the entries in the csv file that do not have a firstname and lastname, I would like the firstname to be set to “name” and the lastname to be set to “Unknown1”, “Unknow2”, Unknown3” etc.  My problem is I can’t figure out how to do this.  Any help would be greatly appreciated.

Thanks
Nick
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
How about:

$cnt = 0
Foreach ($contact in $Contacts)
{
  $cnt++
  if ($contact.firstname  -eq "") {
    $name = "name" + " " + "Unknown" + $cnt
  } else {
    $name = $contact.firstname + "" + $contact.lastname
    $email = $contact.emailaddress
  }

  New-MailContact -Name $name -FirstName $contact.firstname -LastName $contact.lastname -ExternalEmailAddress $email -OrganizationalUnit "summitlan.states/test"

}

Author

Commented:
That worked great