Powershell: List all Mailboxes and Export

In a previous post I covered how to do this with Distribution Lists. Now I want to do the same thing for user mailboxes, however the code ended up being a little bit different since I want to key off of Primary SMTP Address vs. just the name. Since the email address has an @ sign in it, the code changes because it exports differently.

This particular code snippet gets all Mailboxes in Exchange and dumps them to a file. Easily modifiable for other purposes if you need to:

$results=@()
$results+="smtp"
foreach ($item in $(get-mailbox -resultsize unlimited)){$results+=[string]$item.PrimarySMTPAddress}
$results|out-file c:\migration\userout.txt

Let’s break this down a little bit:

$results=@() <== explicitly creates an array for population later

$results+=”smtp” <== because of what I want to do with the export file later, I want a header in this file. This line just creates the initial header.

foreach ($item in $(get-mailbox -resultsize unlimited)){$results+=[string]$item.PrimarySMTPAddress} <== Several things going on in this line. I like combining statements into as little possible code as I can, so this one can be confusing if you don’t know how to look at it

  • foreach (blah in blah){blah} <==typical for each statement that does the {} for every item in the list
  • $item in $(get-mailbox -resultsizeunlimited) <== Pulls every mailbox with no limitations and puts them into the array

$results+=[string]$item.PrimarySMTPAddress <== Pulls the Primary SMTP attribute from every mailbox and adds it into the array defined above. Had to convert it to a string so that it would export in the correct format

$results|out-file filename.txt <== Outputs the results of the array into a textfile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s