Wednesday, September 18, 2013

Powershell - Draw a random mailbox for testing

9/18/2013: Here's something I make use of for quick-evaluating mailbox server health, immediately after a switchover/failover or returning a system to online status after a maintenance outage:

Draw a random (non-monitoring) mailbox for testing:
# Assign the target database identity string to a variable
$TargDB = "Server1\Sg1\Db1"
# Retrieve all matching mailboxes,
# that do not contain a distictinve DisplayName string
# that indicates a monitoring-type mailbox
# (in this case '-NOC-' for 'Network Operations Center') .
$Mailboxes = Get-Mailbox -Database $TargDB -ResultSize "Unlimited" |
Where-Object {$_.DisplayName -notlike "-NOC-*"}
# initate a randomizer & retrieve an integer between
# 0 and retrieved mailboxes count, less one
$iRandMbx = New-Object System.Random
$iRandMbx = $iRandMbx.Next(0, ($Mailboxes.Count - 1))
# perform some task with the matching mailbox;
# in this case, run a test on Exchange Search
# function for the mailbox.
write-host ("Random Mbx: Name:'"+($Mailboxes[$iRandMbx])+"', Acct:'"+($Mailboxes[$iRandMbx]).samaccountname + "'")
write-host "Run: " test-exchangesearch -Identity $Mailboxes[$iRandMbx]
test-exchangesearch -Identity $Mailboxes[$iRandMbx]
Typical Output:
Random Mbx: Name:'Walker, Test', Acct:'WalkerTest'
Run:  test-exchangesearch -Identity Walker, Test

                            ResultFound                              SearchTime
                            -----------                              ----------
                                   True                                     115

Note:I'd be remiss in the above, if I didn't point out that another simple way exists to draw a random object in Powershell V2+, without relying on the  System.Random object used in the code above: You can make use of the new get-random cmdlet. Feed it some form of array of values, or a range, and it will draw one at random:

Get-MailboxDatabase | where {$_.ExchangeVersion.ExchangeBuild.Major -eq 14}| get-random | get-mailbox | get-random

But, in spite of a good alternative being available, I still tend to use the older object, because I frequently need my code to run on a variety of revisions of Powershell, and Exchange, and a decent 'functional' if older alternative is often less trouble and more dependable in the long run than the latest and greatest options. :D

No comments:

Post a Comment