Tuesday, July 24, 2012

Query Recently Created Mailboxes or Users

You may at some point have a need to query recently created mailboxes. This script queries mailboxes created within the last seven days.

$date=(get-date).adddays(-7)
Get-Mailbox –Filter {WhenCreated –gt $date}
The logic of the script is this:
  • Set the variable $date equal to the current date minus 7 days.
  • Get a list of mailboxes with a WhenCreated attribute greater than the date 7 days ago
You can use the same basic structure for other objects such as Active Directory users by substituting the Get-ADUser cmdlet for the Get-Mailbox cmdlet.

$date=(get-date).adddays(-7)
Get-ADUser –Filter {WhenCreated –gt $date}
Update (Dec 2015):
The above syntax actually doesn't work. Not sure how I missed it when I first wrote the post. Today when I was writing a script using this syntax, it returned all mailboxes no matter what. So, the $date variable wasn't being properly evaluated. I'm leaving the above example so that people can see what syntax not to use.

Use the following syntax instead:
$date=(get-date).adddays(-7)
Get-Mailbox –Filter "WhenCreated –gt '$date'"
Apparently when building a filter with a variable, you need to enclose the whole filter in double quotes and the variable in single quotes. This syntax worked properly for me.

No comments:

Post a Comment