1.Find mailboxes with no login in over 30 days and output list to a txt file. Edit the path to your mailbox database and path to txt file output:
Get-MailboxStatistics | where {$_.Database -eq "Server1\StorageGroup1\MailboxDatabase1" -and $_.LastLogonTime -lt (get-date).addDays(-90) -and $_.ObjectClass -eq "Mailbox"} | sort-object lastlogontime | ft DisplayName >C:\Exchange\Cleanup\NoLogin90Days.txt
2.Use ".TrimEnd" to clean up trailing spaces and rewrite the cleaned up txt file:
$list1 = get-content C:\Exchange\Cleanup\NoLogin90Days.txt
$list1 | foreach {$_.TrimEnd()} > C:\Exchange\Cleanup\NoLogin90Days.txt
3.Disable the mailboxes that were in the NoLogin90Days.txt file:
get-content "C:\Exchange\Cleanup\NoLogin90Days.txt" | disable-mailbox
Now, you're correct that I could just take the output from step 1 and go straight into step 3. HOWEVER, I'd like to be able to review the list of inactive users, and edit the list if needed to avoid disabling any system or service mailboxes that don't actually have users logging into them.
Another task I use this for is to move the inactive accounts to mailbox servers with more space. I usually run this before step 3 above:
get-content "C:\Exchange\Cleanup\NoLogin90Days.txt" | move-mailbox -targetdatabase "Server2\StorageGroup2\MailboxDatabase2"
I strongly recommend that you please test these commands in a test environment before running them on your production systems. I've tested functionality on Exchange 2007 and 2010, but your environment may differ.
Rick Estrada
Pastebin for reference: