Get-RemoteMailbox Multiple Domain

Sometimes we need to get the mailbox status for multiple users. Running get-remotemailbox from our exchange server do not query both child domains. Had to come up with a simple script that will query both domain and write the output to a csv file.

$Log = “C:\Users\username\OneDrive – corp\Desktop\Scriptoutput”

$users= Import-Csv “C:\Users\username\OneDrive – corp\Desktop\ScriptInput\Users.csv”

$ExchangeServer = “ExchServer”
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$ExchangeServer/PowerShell/ -Authentication Kerberos -ErrorAction Stop
Import-PSSession -Session $Session -CommandName RemoteMailbox -AllowClobber

foreach ($user in $users) {
$user = $user.samaccountname

$a = Get-RemoteMailbox -identity $user -DomainController domain1.corp -ErrorAction SilentlyContinue

if ( $a.RecipientTypeDetails -eq ‘RemoteUserMailbox’ )
{
# Write to log file here instead of at the end of the previous get-remotemailbox command, you could easily use $a here:
$a | select-object Name, SamAccountname, RecipientTypeDetails, RemoteRecipientType, RemoteRoutingAddress, UserPrincipalName, LegacyExchangeDN, WhenCreated | export-csv -path “$log\mailboxstatusDomain1.csv” -Append -NoTypeInformation
} else {
# Here you will check the 2nd domain:
$b = Get-RemoteMailbox -identity $user -DomainController domain2.corp -ErrorAction SilentlyContinue
if ( $b.RecipientTypeDetails -eq ‘RemoteUserMailbox’ )
{
# Write to log file here with $b
$b | select-object Name, SamAccountname, RecipientTypeDetails, RemoteRecipientType, RemoteRoutingAddress, UserPrincipalName, LegacyExchangeDN, WhenCreated | export-csv -path “$log\mailboxstatusDomain2.csv” -Append -NoTypeInformation
} else {
# Finally, if you’ve reached this else statement, write ‘no results’ to your log file.
echo “Cant find user $user on domain1 and domain2” | Out-File “$log\NoResult.txt” -Append
}
}

}

Posted in Scripts

Write a comment