Hmm not working.. exchange get-mailcontact

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

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.

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

/

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
}

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

            }

Thanks Ben / simon, worked a treat…