Wednesday, 28 September 2016

Find Last Logon Time for Office 365 Users using Powershell

Getting last logon date of all Office 365 Mailbox enabled users is one of the important task to track user logon activity and find inactive users to calculate the Exchange Online license usage. We can use the Exchange Online powershell cmdlet Get-MailboxStatistics to get last logon time, mailbox size, and other mailbox related statistics data.

Before proceed, first we need to connect Remote Exchange Online powershel module by running below command:
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Run the following command to get mailbox statistics for a single Office 365 user
Get-MailboxStatistics -Identity <name or upn of user>
To find last logon time for all the Office 365 users, first we need to get all mailboxes by using Get-Mailbox cmdlet and pipe the results to Get-MailboxStatistics.
Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName,LastLogonTime
Using above script, you can get output only from the cmdlet Get-MailboxStatistics and you can't fetch any result from Get-Mailbox. If you want to read detail from Get-Mailbox command like UserPrincipalName, you need to merge output of two cmdlets.
$mailboxes = Get-Mailbox -ResultSize Unlimited
$mailboxes | ForEach-Object {
$mbx = $_
$mbs = Get-MailboxStatistics -Identity $mbx.UserPrincipalName | Select LastLogonTime
if ($mbs.LastLogonTime -eq $null){
$lt = "Never Logged In"
}else{
$lt = $mbs.LastLogonTime }

New-Object -TypeName PSObject -Property @{ 
UserPrincipalName = $mbx.UserPrincipalName
LastLogonTime = $lt }
}

Export Last Logon Time of Office 365 Users to CSV file:

You can also export all Exchange Online user's last logon time to csv file by using below script
$Result=@() 
$mailboxes = Get-Mailbox -ResultSize Unlimited
$totalmbx = $mailboxes.Count
$i = 1 
$mailboxes | ForEach-Object {
$i++
$mbx = $_
$mbs = Get-MailboxStatistics -Identity $mbx.UserPrincipalName | Select LastLogonTime
if ($mbs.LastLogonTime -eq $null){
$lt = "Never Logged In"
}else{
$lt = $mbs.LastLogonTime }

Write-Progress -activity "Processing $mbx" -status "$i out of $totalmbx completed"

$Result += New-Object PSObject -property @{ 
Name = $mbx.DisplayName
UserPrincipalName = $mbx.UserPrincipalName
LastLogonTime = $lt }
}

$Result | Export-CSV "C:\\O365-LastLogon-Info.csv" -NoTypeInformation -Encoding UTF8

Advertisements
Advertisements

No comments:

Post a Comment