Skip navigation

Recently I was trying to do some routine administrative work via Exchange OWA ECP and received this error:

useless-ecp-error

Hmm… that’s not very useful.

Looking in the Exchange logs this was the corresponding error:

Log Name: Application
Source: MSExchange Control Panel
Date: 3/30/2016 9:00:59 AM
Event ID: 4
Task Category: General
Level: Error
Keywords: Classic
User: N/A
Computer: exchange.domain.bloopblopbloop.com
Description:
Current user: 'CMC\backup'
Request for URL 'https://webmail.bloopblopbloop.com/ecp/default.aspx' failed with the following error:
System.TypeInitializationException: The type initializer for 'Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor' threw an exception. ---> System.FormatException: Input string was not in a correct format.
 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
 at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
 at System.Diagnostics.PerformanceCounterLib.GetStringTable(Boolean isHelp)
 at System.Diagnostics.PerformanceCounterLib.get_NameTable()
 at System.Diagnostics.PerformanceCounterLib.get_CategoryTable()
 at System.Diagnostics.PerformanceCounterLib.CategoryExists(String machine, String category)
 at System.Diagnostics.PerformanceCounterCategory.Exists(String categoryName, String machineName)
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor..cctor()
 --- End of inner exception stack trace ---
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor.LogActivity(CounterType counterType, String organizationName)
 at Microsoft.Exchange.Management.ControlPanel.RbacContext.CreateSession()
 at Microsoft.Exchange.Management.ControlPanel.RbacSettings.CreateSession()
 at Microsoft.Exchange.Management.ControlPanel.AuthenticationSettings..ctor(HttpContext context)
 at Microsoft.Exchange.Management.ControlPanel.RbacModule.Application_PostAuthenticateRequest(Object sender, EventArgs e)
 at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
 at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
System.FormatException: Input string was not in a correct format.
 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
 at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
 at System.Diagnostics.PerformanceCounterLib.GetStringTable(Boolean isHelp)
 at System.Diagnostics.PerformanceCounterLib.get_NameTable()
 at System.Diagnostics.PerformanceCounterLib.get_CategoryTable()
 at System.Diagnostics.PerformanceCounterLib.CategoryExists(String machine, String category)
 at System.Diagnostics.PerformanceCounterCategory.Exists(String categoryName, String machineName)
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor..cctor()
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
 <System>
 <Provider Name="MSExchange Control Panel" />
 <EventID Qualifiers="49152">4</EventID>
 <Level>2</Level>
 <Task>1</Task>
 <Keywords>0x80000000000000</Keywords>
 <TimeCreated SystemTime="2016-03-30T16:00:59.000Z" />
 <EventRecordID>3518828</EventRecordID>
 <Channel>Application</Channel>
 <Computer>exchange.domain.bloopblopbloop.com</Computer>
 <Security />
 </System>
 <EventData>
 <Data>CMC\backup</Data>
 <Data>https://webmail.bloopblopbloop.com/ecp/default.aspx</Data>
 <Data>System.TypeInitializationException: The type initializer for 'Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor' threw an exception. ---&gt; System.FormatException: Input string was not in a correct format.
 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&amp; number, NumberFormatInfo info, Boolean parseDecimal)
 at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
 at System.Diagnostics.PerformanceCounterLib.GetStringTable(Boolean isHelp)
 at System.Diagnostics.PerformanceCounterLib.get_NameTable()
 at System.Diagnostics.PerformanceCounterLib.get_CategoryTable()
 at System.Diagnostics.PerformanceCounterLib.CategoryExists(String machine, String category)
 at System.Diagnostics.PerformanceCounterCategory.Exists(String categoryName, String machineName)
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor..cctor()
 --- End of inner exception stack trace ---
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor.LogActivity(CounterType counterType, String organizationName)
 at Microsoft.Exchange.Management.ControlPanel.RbacContext.CreateSession()
 at Microsoft.Exchange.Management.ControlPanel.RbacSettings.CreateSession()
 at Microsoft.Exchange.Management.ControlPanel.AuthenticationSettings..ctor(HttpContext context)
 at Microsoft.Exchange.Management.ControlPanel.RbacModule.Application_PostAuthenticateRequest(Object sender, EventArgs e)
 at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
 at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)
System.FormatException: Input string was not in a correct format.
 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&amp; number, NumberFormatInfo info, Boolean parseDecimal)
 at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
 at System.Diagnostics.PerformanceCounterLib.GetStringTable(Boolean isHelp)
 at System.Diagnostics.PerformanceCounterLib.get_NameTable()
 at System.Diagnostics.PerformanceCounterLib.get_CategoryTable()
 at System.Diagnostics.PerformanceCounterLib.CategoryExists(String machine, String category)
 at System.Diagnostics.PerformanceCounterCategory.Exists(String categoryName, String machineName)
 at Microsoft.Exchange.Configuration.TenantMonitoring.TenantMonitor..cctor()
</Data>
 </EventData>
</Event>

 
A quick search brought up a few options including “delete your OWA instance and start from scratch”. Thanks, but no thanks. The following solution did the trick for me:

solution


									

Adding Litigation Hold:

get-mailbox | Set-Mailbox -LitigationHoldEnabled $true

 

Removing Litigation Hold:

get-mailbox | Set-Mailbox -LitigationHoldEnabled $false

After a recent migration from Exchange 2003 to Exchange 2010, it was discovered that:

1.) Any new users to Exchange 2010 were not showing up in the GAL of desktop users’ Outlook.

2.) Upon a manual download address book in Outlook, the task would hang.

Neither of these issues were affecting send/receiving of mail. It was more of a nuisance than anything.

It probably didn’t help that we had run the latest service pack for Exchange 2010 too, which had broken all web access (it set all the sites to redirect – a simple unchecking of the “redirect requests to this destination” of all the virtual sites under the default web site in IIS fixed that issue).

During my investigation of the issues, I discovered that the address lists were listed as legacy. This was determined by running the following command in the Exchange Management Shell.

[PS] C:\Windows\system32> Get-AddressList | Format-List Name,*Recipient Filter*,ExchangeVersion

Name                      : All Users

RecipientFilter            : LdapRecipientFilter        : (& (| (mail=*) (proxyAddresses=*) (textEncodedORAddress=*)) (| (& (objectCategory=person) (objectClass=user)) )) LastUpdatedRecipientFilter :

RecipientFilterApplied     : False

RecipientFilterType        : Legacy

ExchangeVersion            : 0.0 (6.5.6500.0)

Applying the following command to all the effected address lists updated them to the latest version.

[PS] C:\Windows\system32>Set-Addresslist “All Users” -IncludedRecipients Mailboxusers

Confirm

To save changes on object “All Users”, the object must be upgraded to the current Exchange version. After the upgrade, this object cannot be managed by an earlier version of the Exchange Management Tools. Do you want to continue to upgrade and save the object?

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [?] Help (default is “Y”): y

Running a quick check showed that the RecipientFilterType had been updated.

[PS] C:\Windows\system32>Get-AddressList | Format-List Name,*RecipientFilter*,ExchangeVersion

Name                       : All Users

RecipientFilter            :RecipientType -eq ‘UserMailbox’ LdapRecipientFilter        : (&(objectClass=user)(objectCategory=person)(mailNickname=*)(msExchHomeServerName=*))

LastUpdatedRecipientFilter : RecipientType -eq ‘UserMailbox’

RecipientFilterApplied     : True

RecipientFilterType        : Precanned

ExchangeVersion            : 0.1 (8.0.535.0)

While this didn’t fix any of my issues, it was something that should have been done and was preventing me from editing the address lists.

Opening ASDIedit.msc, I navigated to the new users that were not showing up in the GAL and looked at their properties – specifically the “showInAddressBook” attribute. The new users showed this being set to the “All Users” address list instead of the “Default Global Address List”. Why this is happening, I still have some research to do. However, by running the cmdlet to update the email address policy on the affected users, the attribute was fixed (I suppose you could do this by hand too).

[PS] C:\Windows\system32>update-emailaddresspolicy -identity “Default Policy”

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/Internet Newsgroups” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/Internet Newsgroups 93126049” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/OAB Version 2” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/OAB Version 2-1” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/OAB Version 3a” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/OAB Version 4” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/Offline Address Book – \/o=<domain>\/cn=addrlis” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/Offline Address Book – <domain>” is invalid and couldn’t be updated.

WARNING: The recipient “<domain>/Microsoft Exchange System Objects/Schedule+ Free Busy Information – <domain>” is invalid and couldn’t be updated.

[PS] C:\Windows\system32>set-mailbox -applymandatoryproperties -identity “<user name>” -v

VERBOSE: [19:10:53.160 GMT] Set-Mailbox : Active Directory session settings for ‘Set-Mailbox’ are: View Entire Forest: ‘False’, Default Scope: ‘<domain>’, Configuration Domain Controller: ‘<DC>’, Preferred Global Catalog: ‘<DC>’, Preferred Domain Controllers: ‘{<DC>}’

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Runspace context: Executing user: <domain>/Users/<Admin>, Executing user organization: , Current organization: , RBAC-enabled: Enabled.

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Beginning processing &

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Instantiating handler with index 0 for cmdlet extension agent “Mailbox Creation Time Agent”.

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Instantiating handler with index 1 for cmdlet extension agent “Query Base DN Agent”.

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Instantiating handler with index 2 for cmdlet extension agent “Rus Agent”.

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Instantiating handler with index 3 for cmdlet extension agent “Admin Audit Log Agent”.

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Current ScopeSet is: { Recipient Read Scope: {{, }}, Recipient Write Scopes: {{, }}, Configuration Read Scope: {{, }}, Configuration Write Scope(s): {{, }, }, Exclusive Recipient Scope(s): {}, Exclusive Configuration Scope(s): {} }

VERBOSE: [19:10:53.175 GMT] Set-Mailbox : Searching objects “<user name>” of type “ADUser” under the root “$null”.

VERBOSE: [19:10:53.191 GMT] Set-Mailbox : Previous operation run on domain controller ‘<DC>’.

VERBOSE: [19:10:53.207 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Update Recipient object “<domain>/Staff/<user name>” with ConfigurationDomainController “<null>”, DomainController “<DC>”, GlobalCatalog “<null>”.

VERBOSE: [19:10:53.207 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Read Address List for organization “” from domain controller <DC>.

VERBOSE: [19:10:53.207 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\Default Global Address List”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\All Rooms”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\All Users”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\All Groups”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\All Contacts”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Address List “\Public Folders”.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Add Address List “\Default Global Address List” to AddressListMemberShip of the recipient.

VERBOSE: [19:10:53.222 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Read Email Address Policy for organization “” from domain controller <DC>.

VERBOSE: [19:10:53.238 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Email Address Policy “<policy name>”.

VERBOSE: [19:10:53.238 GMT] Set-Mailbox : [Microsoft Cmdlet Extension Agent] Found Email Address Policy “Default Policy”.

VERBOSE: [19:10:53.238 GMT] Set-Mailbox : Failed to find the address type object in Active Directory for address type “MS:AMD64”.

VERBOSE: [19:10:53.253 GMT] Set-Mailbox : Processing object “<domain>/Staff/<user name>”.

VERBOSE: [19:10:53.253 GMT] Set-Mailbox : Admin Audit Log: Entered Handler:Validate.

VERBOSE: [19:10:53.253 GMT] Set-Mailbox : Admin Audit Log: Exited Handler:Validate. VERBOSE: Setting mailbox “<user name>”.

VERBOSE: [19:10:53.253 GMT] Set-Mailbox : Resolved current organization: .

VERBOSE: [19:10:53.269 GMT] Set-Mailbox : The properties changed on the object ‘<user name>’ (CN=<user name>,OU=Staff,DC=<domain>) are: “{ AddressListMembership[showInAddressBook]={ ‘\All Contacts’, ‘\Public Folders’, ‘\All Rooms’, ‘\All Groups’, ‘\All Users’, ‘\Default Global Address List’ }, ReadOnlyAddressListMembership[showInAddressBook]={ ‘\All Contacts’, ‘\Public Folders’, ‘\All Rooms’, ‘\All Groups’, ‘\All Users’, ‘\Default Global Address List’ } }”.

VERBOSE: [19:10:53.269 GMT] Set-Mailbox : Saving object “<domain>/Staff/<user name>” of type “ADUser” and state “Changed”.

VERBOSE: [19:10:53.285 GMT] Set-Mailbox : Previous operation run on domain controller ‘<DC>’.

VERBOSE: [19:10:53.285 GMT] Set-Mailbox : Admin Audit Log: Entered Handler:OnComplete.

VERBOSE: [19:10:53.300 GMT] Set-Mailbox : Admin Audit Log: Exited Handler:OnComplete.

VERBOSE: [19:10:53.300 GMT] Set-Mailbox : Ending processing &

Running the command in verbose mode with the -v flag will display the specifics on what attributes were changed.

Checking in Outlook, issue #1 was solved.

The second issue, the issue with the download of the OAB (offline address book) hang in Outlook turned out to be a permissions issue in IIS on the Exchange server. Opening up the IIS manager, navagating to the OAB virtual site, right clicking on it and selecting “explore” will open up the website folder. There should be a “web.config” file included in this location. Check the permissions on this file and add read permissions for “Authenticated Users”. This fixed our issue of Outlook hanging on a manual download. I also checked “require SSL” under the OAB virtual site before modifying the permissions on the web.config file. This may or may not be an issue for you, but as I was checking with 2007, SSL was required.

Note: You will need to restart the web services for these changes to take effect. Also, any users running Outlook in cached mode will not see the changes until their OAB is refreshed.

References:

https://social.technet.microsoft.com/Forums/en-US/exchangesvrgeneral/thread/548f2ecc-faae-4744-8b33-7de536196d7d/

http://www.serkanbark.com/2011/07/the-address-list-couldnt-be-edited/

https://blogs.msdn.com/b/dgoldman/archive/2007/05/24/exchange-2007-objects-are-not-stamped-with-showinaddressbook-and-never-end-up-in-the-gal-after-a-gal-sync.aspx

During a recent migration from Windows 2003 to 2008, and subsequent updating of various scheduled scripts, I came across an issue with my scripts not functioning when executed through the task scheduler. The problem, as it turns out, is how Windows 2008 task scheduler handles mapped drives. I don’t know exactly what was changed between 2003 and 2008 in this respect, but the fact is 2008 requires any scripts that need mapped drive access, self mount the desired path.

Here’s an example of the code I added to my Python scripts to get them to be able to run as a scheduled task using mapped drives.

#this module is included in the pywin32 package
import win32wnet
from win32netcon import RESOURCETYPE_DISK as DISK

#drive you want to map to
local_dir = "Z:"          
drive_path = "\\\\network-server\\shared-folder-of-interest"

#mount the mapped drive
win32wnet.WNetAddConnection2(DISK,local_dir,drive_path)

#insert code here to do whatever using mapped drive

#unmount the mapped drive (if you don't do this, the mapped drive will be persistent
#causing this script to hang next time it is scheduled to run again
win32wnet.WNetCancelConnection2(local_dir, 0, 0)

Occasionally I find myself with the need to scan a directory for old files. To aid in this task I came up with this little Python script. It is able to traverse into nested/child directories in order to find all the files for an area of interest. The results are saved to a text file. The formatting could use some work, but for my purposes, it does its job. Also, it should be noted that this program was written for Windows file scanning. However, it should only require minor tweaking to get it to work on other operating systems.

import os, time, operator, sys, getopt, stat, re
gmt = time.gmtime(time.time())
thisyear = time.strftime('%Y',gmt)
matches = []
path, cutoff, sortby, verbose, check = "", 0, "", 0, 0

def usage():
 # prints usage statement
 print "\ndirscan.py [options]\n"
 print "  -p PATH             Path to the root directory"
 print "                      where you want the scan to"
 print "                      begin.\n"
 print "  -y YYYY             Scan for files older than"
 print "                      this last modification year.\n"
 print "  -s [date,name,size] Sort by this type -"
 print "                      modification date, "
 print "                      directory/file name, "
 print "                      or file size.\n"
 print "  -i                  Interactive mode. You will"
 print "                      be prompted for values.\n"
 print "  -v                  Verbose mode - display results"
 print "                      on screen (will still be saved"
 print "                      to file.\n"
 print "  -h                  This usage page.\n"
 print "\n Example: dirscan.py -p \"u:/scripts\" -y 2006 -s size"
 sys.exit()

def interactive():
 # interactively prompts user for search criteria
 global path, cutoff, sortby, check
 print "Search Criteria:"
 print "Path? (no quotes required): "
 path = sys.stdin.readline().rstrip('\n')
 check = check + 1

 print "Older than year [yyyy]?: "
 cutoff = sys.stdin.readline().rstrip('\n')
 check = check + 1

 print "Sort results by [date, name, size]?: "
 sortby = sys.stdin.readline().rstrip('\n')
 check = check + 1

# Crawls the directory stucture,
def lister(dummy, dirname, filesindir):
 print "Scanning --> [" + dirname + "]"
 try:
 for fname in filesindir:
 filepath = os.path.join(dirname, fname)

 # Searches for files that match the criteria
 if os.path.isfile(filepath): 
 filestats = os.stat(filepath)
 fileyear = time.strftime('%Y',time.localtime(os.path.getmtime(filepath)))
 if int(fileyear) <= int(cutoff):
 filectime = time.strftime("%Y/%m/%d %I:%m:%S",time.localtime(filestats[stat.ST_CTIME]))
 filemodtime = time.strftime("%Y/%m/%d",time.localtime(filestats[stat.ST_MTIME]))
 fileacctime = time.strftime("%Y/%m/%d %I:%m:%S",time.localtime(filestats[stat.ST_ATIME]))
 fsize = int(os.path.getsize(filepath)/1024.0)
 matches.append([filepath,filectime,filemodtime,fileacctime,fsize])
 except ValueError:
 print dirname + " was not included in the list"
try:
 opts, args = getopt.getopt(sys.argv[1:], "ihp:y:s:v", ["interactive","help", "path=", "cutoff=","sortby="])
 if not opts:
 print "ERROR!\nOptions not specified"
 usage()
 for o, a in opts:
 if o in ("-p", "--path"):
 path = a
 check = check + 1
 if o in ("-y", "--year"):
 cutoff = int(a)
 check = check + 1
 if o in ("-s", "--sortby"):
 sortby = a
 check = check + 1
 if o == "-i":
 interactive()
 if o in ("-h", "--help"):
 usage()
 if o == "-v":
 verbose = 1

except getopt.GetoptError, err:
 print "ERROR!\nIncorrect options"
 usage()

if check != 3:
 print "ERROR!\nYou must specify path, date, AND sort type.\n"
 usage()

os.path.walk(path, lister, None)

# Sort the matches
if sortby == 'name':
 sortedlist = sorted(matches, key=operator.itemgetter(0))
elif sortby == 'date':
 sortedlist = sorted(matches, key=operator.itemgetter(1))
elif sortby == 'size':
 sortedlist = sorted(matches, key=operator.itemgetter(2),reverse=True)
elif sortby == 'none':
 sortedlist = matches
else:
 print "Unknown sort type - " + sortby + " - sorting by size"
 sortedlist = sorted(matches, key=operator.itemgetter(2),reverse=True) 

# Save the results to a file
if verbose == 1:
 print "\nResults:"
save_results = open('results.txt','w')
save_results.write('Path, Creation Date, Last Modification Date, Last Access Date, Size(KB)\n')
save_results.write('--------------------------------------\n')
atab = "\t"
for item in sortedlist:
 if verbose == 1:
 print item
 for entry in item:
 save_results.write(str(entry) + atab)
 save_results.write('\n')
print "\nResults saved to file (results.txt)"
save_results.close()

Here’s a script I put together for Exchange 2010 to grab the mailbox size for all the users in my Exchange mailbox database, formatted, and saved to a text file.

The big ugly script. Granted, this could be larger and uglier depending upon how many mailbox statistics fields you required. For my purposes, this was all that was needed.

Get-MailboxStatistics -database ‘Exchange Mailbox Database’ | where {$_.ObjectClass -eq “Mailbox”} | Sort-Object TotalItemSize -Descending | ft @{label=”User”;expression={$_.DisplayName}},@{label=”Total Size (MB)”;expression={$_.TotalItemSize.Value.ToMB()}}  -auto >> “c:\mailbox_size.txt”

As lovely as that is, let’s break it down so you have a better idea what exactly is happening.

Get-MailboxStatistics

This cmdlet is a handy way to show the stats for specific mailboxes (as the command suggests).

Get-MailboxStatistics -database ‘Exchange Mailbox Database’

This uses the get-mailboxstatistics cmdlet and specifies that we want to grab the data from the ‘Exchange Mailbox Database’. Obviously this will change depending on what your mailbox is called. When in doubt you can run get-mailboxdatabase to find out what your databases are labeled.

| where {$_.ObjectClass -eq “Mailbox”}

Next, we pipe this data to a conditional. In this case we want to grab just the mailboxes.

| Sort-Object TotalItemSize -Descending | ft @{label=”User”;expression={$_.DisplayName}},@{label=”Total Size (MB)”;expression={$_.TotalItemSize.Value.ToMB()}}

This one is a bit hairy. Basically we are then piping the mailbox data to get sorted. Specifically we want to sort in a descending order by mailbox size then name. You may notice this bit of code: $_.TotalItemSize.Value.ToMB() That is converting the mailbox size (which is stored as bytes) to MB. We also add some handy labels to the top of the display so we know what it is exactly we are looking at when we happen to stumble upon this file a year down the road or have to send it of to someone else to decipher. Labels. Know them, use them, love them.

-auto

This auto-formats the display. Try running the script without it, you’ll see what I mean.

>> “c:\mailbox_size.txt”

And lastly, we throw the output into a text file. The ‘>>’ creates a new text file if one didn’t already exist. If it does exist, it will append the new output to the end of the current file. Likewise, if you just want to create a new file each time (no append) then you would want to use ‘>’ instead.

You can find a good description of the get-mailboxstatistics cmdlet over at this TechNet page. There’s also a handy guide on this at Petri as well.

Create your own website, free on WordPress.com.Create your own website.
Start free