Forum Discussion

dewandtcutterbuckcom's avatar
dewandtcutterbuckcom
Copper Contributor
Apr 05, 2023

Export 365 Users last logon time using powershell

I have created a PowerShell command that is supposed to export every users last logon time that is greater than 1 day. But it continues to create a blank document. Below is the command.

 

 

Get-Mailbox -RecipientType 'UserMailbox' |%{ Get-MailboxStatistics $_.UserPrincipalName | Sort-Object LastLogonTime | Where {$_.LastLogonTime -lt ([System.DateTime]::Now).AddDays(-1) } | Export-Csv "C:\Logs\O365MAILBOXSTATS_REPORT1.CSV" -NoTypeInformation -Append}

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    dewandtcutterbuckcom 

     

    You're close, but where you've gone wrong is putting everything inside the ForEach-Object block. The Sort-Object and Export-Csv belong outside of that block, not in it.

     

    I'm not sure why your file is empty other than nothing has a LastLogonTime older than one day. Try leaving out the Sort-Object and Export-Csv sections to see if any results are being returned.

     

    Here's an example of how the blocks should be arranged:

     

     

    Get-EXOMailbox -PropertySets StatisticsSeed -ResultSize unlimited |
        Get-EXOMailboxStatistics -PropertySets Minimum -Properties LastLogonTime |
            Where-Object {
                $_.LastLogonTime -lt [datetime]::Now.AddDays(-1);
            } |
                Select-Object -Property LastLogonTime, MailboxGuid, DisplayName |
                    Sort-Object -Property LastLogonTime |
                        Export-Csv -NoTypeInformation -Path "C:\Data\Temp\blah.csv";

     

     

    Cheers,

    Lain

     

    Edited to account for the -Append switch on the CSV export, which I didn't originally spot.

  •  

    dewandtcutterbuckcom 

     

    This script should do it for you 🙂

     

     

    # Import Active Directory module
    Import-Module ActiveDirectory
    
    # Get all user accounts and their last logon timestamps
    $users = Get-ADUser -Filter * -Properties LastLogonTimestamp
    
    # Filter out users who have logged on within the last 24 hours
    $users = $users | Where-Object {($_.LastLogonTimestamp -ne $null) -and ((Get-Date) - (Get-Date $_.LastLogonTimestamp)).TotalHours -gt 24}
    
    # Convert timestamps to a human-readable format
    $users = $users | Select-Object Name, @{Name="LastLogon"; Expression={(Get-Date $_.LastLogonTimestamp -Format "yyyy-MM-dd HH:mm:ss")}}
    
    # Export results to a CSV file
    $users | Export-Csv -Path LastLogon.csv -NoTypeInformation

     

Resources