Wednesday, 11 December 2019

Powershell - compare two mailboxes in hash table and export to CSV

 

I thought I’d share a useful little powershell trick I used today which allowed me to easily compare two very similar mailboxes in Office 365.  I had a user who had a duplicate mailbox which had been inadvertently created through an issue with AAD Sync.  I knew all the fields I would be comparing would be identical so I used a hash table with embedded arrays to compare the information I was interested in. 

 

First create a variable for each mailbox which will contain all the information we will be comparing.  Then create the hashtable.

 

 

$user1 =  get-mailbox -identity user.name@contoso.com

$user2 =  get-mailbox -identity user.name@contoso-corp.com

$combined = @{}

 

Next pipe the fields from the variable into the hash table, creating an array for each one.  Then pipe the variables containing our mailbox data into the nested arrays in the hashtable.

 

 

$user1.psobject.properties | Foreach { $combined[$_.Name] = @() }

$user1.psobject.properties | Foreach { $combined[$_.Name] += $_.Value }

$user2.psobject.properties | Foreach { $combined[$_.Name] += $_.Value }

 

 

Finally I converted the hashtable back to a PSObject so that I could export it to a csv file and analyse the output in Excel.

 

$combined.getenumerator() | ForEach-Object {

    New-Object -Type PSObject -Property @   {

        'Field' = $_.Name

        'contoso.com' = $_.Value[0]

        'contoso-corp.com' = $_.Value[1]

                                            }

    } | Select-Object Field, contoso.com, contoso-corp.com | Export-Csv C:\cloudwyse\comparison.csv -NoType

   

 

The whole (short) script is available in the Gist below.

 

No comments:

Post a Comment