Get last logon and email address from Exchange logs

I have created a PS script below which searches within our federated domain for a specific domain, and outputs the last login

Get-Mailbox -RecipientTypeDetails UserMailbox -Resultsize Unlimited |
    where {$_.emailAddresses -like "*@example.co.uk" } |
    Get-MailboxStatistics |
    Select-Object DisplayName,PrimarySmtpAddress,LastLogonTime |
    Export-CSV "C:\temp\O365-LastLogon-Info.csv" -NoTypeInformation -Encoding UTF8

So far it is only pulling the displayname and lastlogin and for some reason it doesn't pull the email address.


Solution 1:

The below PowerShell outputs the expected results in a csv file as you desire. Pipe only the PrimarySmtpAddress property value output of the Get-Mailbox command over to a ForEach-Object loop.

Use a variable to save PrimarySmtpAddress value in the loop and refer back to that with a calculated property naming the column and setting the value in the expression with the output of the Select-Object command.

PowerShell

(Get-Mailbox -RecipientTypeDetails UserMailbox -Resultsize Unlimited | 
    ? { $_.emailAddresses -like "*@uspotus.us" }).PrimarySmtpAddress | % {
        $p = "";
        $p = $_;
        $_ | Get-MailboxStatistics | Select DisplayName, @{N='PrimarySmtpAddress'; E={$p}}, LastLogonTime;
        } | Export-CSV "C:\temp\O365-LastLogon-Info.csv" -NoTypeInformation -Encoding UTF8;

Output example

DisplayName   PrimarySmtpAddress LastLogonTime        
-----------   ------------------ -------------        
Barrack Obama [email protected]  11/4/2021 11:18:11 PM

Supporting Resources

  • Calculated_Properties

  • Add a calculated property with Select-Object in PowerShell

  • Where-Object

    The '?' symbol and Where are both aliases for Where-Object. If you explicitly want to run the Where-Object command, run Where-object or '?'

  • ForEach-Object

    Standard Aliases for Foreach-Object: the '%' symbol, ForEach

  • Select-Object

    Standard Aliases for Select-Object: select