PowerShell's Get-Random commandlet, a practical example

So I had an issue the other day in which a client needed to export Exchange mail data from all of their mailboxes from a specified time period. At first glance this is a no brainer, just use the New-MailboxExportRequest command with the -ContentFilter {(Received -gt "01/01/2014")} option to nail down the date range.

The wrinkle in this simple request came when they wanted an estimate of how long it was going to take. The idea was that if we grab 100 mailboxes, run the exports and then look at the New-MailboxExportRequestStatistics data we could get a good idea of how much data we're talking about. But do we just select 100 mailboxes? That doesn't seem like a random sample of the data set. That's where the Get-Random command came in handy.

So the Get-Random command simply returns a random element of a variable. You feed it an array and it grabs one randomly. In our case we grabbed all of the mailboxes and stuffed them into an array of objects by using the command:
               $mailboxes=Get-Mailbox -Resultsize unlimited

Now that we have the variable set up we need to we use Get-Random to grab a random mailbox.
               $mailboxes | Get-Random

This is great but since we want 100 random elements we would have an issue in that running Get-Random multiple times can return the same entry more than once. Obviously the odds of getting duplicates depends on the data size but it's possible which is less than optimal.

It turns out that Get-Random has a mechanism to handle the need for sample sets. All we have to do is use the -Count parameter to define the number of random elements we want without having duplicates. For our example we would need to use the Get-Random with a -count of 100.
               $mailboxes | Get-Random -count 100

Or the best way to do it would be to use the Get-Random before we store the whole set if we only need 100 mailboxes. Like this:
               $mailboxes=Get-Mailbox -Resultsize unlimited | Get-Random -Count 100

So now that we have the random sample in an array we just have to run through a foreach loop like below:
-----------------------------------------

 $mailboxes=get-mailbox -resultsize unlimited | Get-Random -count 100
Foreach($mailbox in $mailboxes) {
    $path="\\EXCSRV03\Exports\Test\" + $mailbox.alias + ".pst"
    New-MailboxExportRequest -Name $mailbox.alias -Mailbox $mailbox.alias -ContentFilter {(Received -gt "01/01/2014")} -FilePath $path
}

Labels: , ,