Author Posts

July 25, 2017 at 6:59 am

Hi All this works to pull back the details of a mail contact however it does not record the $contact.mail if the contact is not found (im excluding mail address's from my own domain in the foreach)

$contacts = import-csv C:\temp\contacts.csv 

$Result = foreach ($contact in $contacts|Where-Object {$_.mail -NotLike "*@domain.com*"})
{

try {

        Get-MailContact $contact.mail
    }

Catch { 

        $contact.mail | out-file c:\temp\contactserrors.txt -Append

       }
    
}

$result | Out-GridView

csv is 1 column with the header "Mail" with rows of email addresses underneath

July 25, 2017 at 7:59 am

A catch block only kicks in on a terminating error. Try using the -ErrorAction switch with the value Stop in your Get-MailContact command in your Try block.

July 25, 2017 at 8:16 am

Thanks Maurice, however -Erroraction does not seem to be supported with get-mailcontact

tried setting error preference with no luck either

$contacts = import-csv C:\temp\contacts.csv 

$Result = foreach ($contact in $contacts|Where-Object {$_.mail -NotLike "*@domain.com*"})
{

try {

        $ErrorPreference='Stop'
        
        Get-MailContact $contact.mail 
    }

Catch { 

        $contact.mail | out-file c:\temp\contactserrors.txt -Append

       }
    
}

$result | Out-GridView

/


	
			
	

July 25, 2017 at 8:30 am

Have you tried it in an if block as opposed to a try catch ?

if (get-mailcontact $contact.mail){
write-host "found contact"
}
else{
$contact.mail | out-file c:\temp\contactserrors.txt -Append
}

July 25, 2017 at 8:41 am

That's not the right use of try catch blocks.
For your task you should do something like this in your foreach loop:

 $MailContact = Get-MailContact $Contact.Mail
     if ($MailContact) {

         Write-Output $MailContact

         } else {

           $Contact.Mail | Out-File .\errors.txt -Append

            }

July 25, 2017 at 9:19 am

Thanks Ben / simon, worked a treat....