none
Exchange 2010 Powershell - Export All Contacts from Selected Users Mailboxes to CSV File

    General discussion

  • I search for several days to find a script for exporting contacts from selected mailboxes using powershell.  I found code snipets here and there and after much work got the export to complete sucessfully.  Here is the code.  I'm hoping it saves someone else the time and frustration I put in. 

    Thanks to all who provided snipits that are pasted together here.

    $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"

    [void][Reflection.Assembly]::LoadFile($dllpath)

    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)

    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()

    $sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"

    $aceuser = [ADSI]$sidbind

    $service.AutodiscoverUrl($aceuser.mail.ToString())

    $outputfile = "c:\ContactExport.csv"

    #Header rows
    '"User","First Name","Last Name","Company","Address1","City","State","Zip","Home Phone 1","Work Phone 1","Cell Phone 1","Fax/Other 1","Email 1","Home Phone 2","Work Phone 2","Email 2"' | Out-File -Encoding ASCII -FilePath $outputfile -append

    #traverse mailbox and pull out All Contacts
    function getcontacts ([string]$MailboxName)
    {
     $ContactsFolderid  = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)
     $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000,0)
     $findResults = $Service.FindItems($ContactsFolderid,$view)

    foreach($item in $findResults)
     {
     """$MailboxName"",""$($item.GivenName)"",""$($item.Surname)"",""$($item.CompanyName)"",""$($item.PhysicalAddresses[0].Street)"",""$($item.PhysicalAddresses[0].City)"",""$($item.PhysicalAddresses[0].State)"",""$($item.PhysicalAddresses[0].PostalCode)"",""$($item.PhoneNumbers[8])"",""$($item.PhoneNumbers[2])"",""$($item.PhoneNumbers[11])"",""$($item.PhoneNumbers[1])"",""$($item.EmailAddresses[0].Address)"",""$($item.PhoneNumbers[9])"",""$($item.PhoneNumbers[3])"",""$($item.EmailAddresses[1].Address)""" | Out-File -Encoding ASCII -FilePath $outputfile -Append }
     }

    #Pulls names from a csv file that you provide

    foreach
    ($MailboxName in Get-Content "c:\UN.txt")
     {
     getcontacts -MailboxName ($MailboxName)
     }

    Wednesday, May 16, 2012 9:15 PM