Getting Information About User's Exchange Mailbox Using VBScript and PowerShell

Friday, September 4, 2009

Here are two short scripts, one in VBScript and the other in PowerShell that search Active Directory and display a user's Exchange server, storage group, and mailbox store.  They work on against any version of Exchange 20xx.

First, the VBScript:
'Mailbox.vbs, v1.00

'This script will display a user's current mailbox server and storage group

Set theArgs = WScript.Arguments
If theArgs.Count > 0 Then strSearch = theArgs.Item(0)
If strSearch = "" Then
    strSearch = InputBox("Please enter the user ID to look up.", "Mailbox Search")
    If strSearch = "" Then WScript.Quit
End If

Set con = CreateObject("ADODB.Connection")
con.Provider = "ADsDSOObject"
con.Open "DS Query"
Set command = CreateObject("ADODB.Command")
Set command.ActiveConnection = con
Command.Properties("searchscope") = 2

command.CommandText = "SELECT AdsPath,homeMDB,name FROM 'LDAP://DC=domain,DC=com' WHERE sAMAccountName = '" & strSearch & "' AND objectclass='User'"

Set rs = Command.Execute

If NOT rs.EOF Then
    mailbox = rs.Fields(1).Value
    mailbox = Left(mailbox, Instr(mailbox, "CN=InformationStore") - 2)
    msg = "User: " & rs.Fields(0) & vbCRLF & "Mailbox: " & mailbox
    MsgBox msg, vbInformation, "Mailbox Search"
    MsgBox "User '" & strSearch & "' not found!", vbCritical, "Mailbox Search"
End If

And here's the same script in PowerShell:
$sam = Read-Host "Enter the user logon name"

$searcher=New-Object DirectoryServices.DirectorySearcher
if ($result -eq $null)
    Write-Host "Logon name not found"
    $a = [string] $
    $b = $a.split(",")
    Write-Host "Exchange Mailbox Server: " $b[3]
    Write-Host "Storage Group: " $b[1]
    Write-Host "Mailbox Database: " $b[0]

Both scripts will take an argument (the user's logon name), and will prompt for it if it was not supplied in the command line.