Hmm not working.. exchange get-mailcontact

This topic contains 5 replies, has 4 voices, and was last updated by  Mark Prior 3 months ago.

  • Author
    Posts
  • #75743

    Mark Prior
    Participant

    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

  • #75745

    Maurice L
    Participant

    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.

  • #75748

    Mark Prior
    Participant

    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
    
    /
    
    
    		
    	
  • #75751

    Simon B
    Participant

    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
    }

  • #75754

    Ben Camareno
    Participant

    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
    
                }
    • #75758

      Mark Prior
      Participant

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

You must be logged in to reply to this topic.