Get Last Logon Time of AzureAD Users PowerShell

Specifically, I am writing get last logon time of AzureAD Users using Powershell for specific cloud admins. Previously, I also wrote on Get Last Logon Time of Office 365 Users using PowerShell while considering that it will audit all users. Then, I found following comments which enforce me to write PowerShell script to get last logon time of AzureAD Users. Meanwhile, I am copying some comments to highlight the reason, I am writing this post.

The provided script gives you the last login information of users who have Exchange Online license whereas the requirement is to display “last logon time” of unlicensed users as well.

What about users who don’t have mailboxes? I have a number of users for whom we have disabled the Exchange Online license. How can I get their logon statistics?

It’s not only unreliable, it’s impossible. Get-MailboxStatistics only returns statistics for mailboxes, but I specifically need logon statistics for people who do not have mailboxes.

AzureADPreview Module

Certainly, AzureADPreview is a Azure Active Directory V2 Preview Module which is required for Get-AzureAdAuditSigninLogs. Therefore, before starting the actual code to get last logon time, you have to do the following.

Install-Module AzureADPreview
Import-Module AzureADPreview

Specifically, I installed AzureADPreview before and then I used Import-Module to get it working.

Get-AzureAdAuditSigninLogs Module

Further, you also need to know that Get-AzureAdAuditSigninLogs cmdlet gets an Azure Active Directory sign in log.

Get Last Logon Time of AzureAD Users

Specifically, You can get last logon time of AzureAD Users using PowerShell with below mentioned PowerShell code snippet.

#Connect AzureAD while using AzureADPreview Module.
AzureADPreview\Connect-AzureAD
$AZUsers = Get-AzureADUser -All $True
$AZUsers | ForEach-Object {
    $User = $_
    $UPN = $User.UserPrincipalName
    
    $LoginTime = Get-AzureAdAuditSigninLogs -top 1 -filter "userprincipalname eq '$UPN'" | select CreatedDateTime
  
    New-Object -TypeName PSObject -Property @{
        DisplayName = $User.DisplayName
        UserPrincipalName = $UPN
        LastSignInDate = $LoginTime.CreatedDateTime}
}

Reference Documents

Above PowerShell code snippet will work without required to visit these reference documents. However, If you need detail about these modules, you can visit these links.

Share

You may also like...