Export Last Login Date: Entra ID/M365 Users with PowerShell

Recently, I was assigned to find the most recent login information for EntraID/Microsoft 365 users. This report aims to identify individuals who haven’t logged into their devices for a long time. My main goal is to determine if a user is still active and disable accounts that haven’t been used in over six months.

This blog post will explore various methods for listing and exporting information on an Entra ID user’s last login date and time. We’ll leverage a PowerShell cmdlet called Get-AzureADAuditSignInLog to achieve this, which is included in the AzureADPreview PowerShell module. This cmdlet enables us to fetch the sign-in logs of Entra ID users.

With the PowerShell cmdlet Get-AzureADAuditSignInLog, you can export all the sign-in data for a user. Below, I’ve outlined some relevant sign-in properties you can retrieve using this cmdlet.

  • User’s Object Id – Entra ID User’s Object ID information
  • Last Sign-in Date and Time – This is the most recent sign-in log date and time information. The property name is CreatedDateTime.
  • User’s Display Name – Display the user’s name information. For example, Jatin Makhija
  • UserPrincipalName – User Principal Name information of the user. For example jatin.makhija@cloudinfra.net
  • Application Display Name: Which application is being used for Authentication? For example: When logging on to a Windows device, It will show as Windows Sign In.
  • Device ID – The user will sign in from a device to authenticate to Entra ID; that device ID will be recorded in the sign-in log.
  • Device Operating system – Device Operating System is used for sign-in. For example: Windows, macOS, etc.
  • Device Compliance status – Compliance Status of the device. For example, IsCompliant: True or False.
  • Device Display Name – Device display name as it shows in Entra ID. For example Cloudinfra-net1
  • Any Authentication Failure Reason: If you want to find out the reason for an authentication failure, you can check this information.
  • IP Address – The device IP Address is also recorded in sign-in logs and retrievable.
  • Client App Used – Check if a thick or thin client is used to log on to Entra ID. This could be a Browser app, Outlook app, Mobile app, or Desktop client.

1. Get the Last Login Date/Time from Entra admin center

To obtain the Last Login Date and Time information of users from the Entra Admin Center, please follow these steps:

  • Sign in to the Entra admin center.
  • Under Identity, Go to Users > All users.
  • Click on a user to check the Last Login information.
  • Click on Sign-in logs on the left-hand side.

To identify the most recent log entry, look at the top of the list and examine the Date column, which displays the user’s last sign-in timestamp.

Get the Last Login Date/Time Information from Entra admin center
Get the Last Login Date/Time Information from Entra admin center

2. Get the Last Login Date/Time Using Powershell [For One User]

As you’ve observed, checking the Last Login Information for a single user through the Entra Admin Center is straightforward. However, when dealing with thousands of users, relying on the graphical user interface (GUI) for this task becomes unmanageable.

We will start by exploring how to retrieve a user’s last login information using PowerShell. Then, we’ll learn how to export the user’s last login information in a text file. Finally, we’ll cover how to export the Last Login information of all Entra ID users.

Before running the Get-AzureADAuditSignInLog PowerShell cmdlet, you must install the Azure AD Preview module and connect it to the Entra ID. Let’s go over the necessary steps:

Install AzureADpreview powershell module

Install-module -name AzureADpreview

Connect to Entra ID/AzureAD

Connect-AzureAD

Get the Last Login date time of an Entra ID user

The following command will retrieve a specific user’s last login date and time. The CreatedDateTime attribute represents the timestamp of the last sign-in log, indicating when the user last connected to EntraID/M365.

Get the Last Login date time of an Entra ID user

Get-AzureADAuditSignInLogs -Filter "startsWith(userPrincipalName,'adelev@cloudinfra.net')" -top 1 | Select UserDisplayName, CreatedDateTime
Get the Last Login Date/Time Information Using Powershell
Get the Last Login Date/Time Information Using Powershell

3. Export the Last Login Date/Time to CSV Using Powershell [For a List of Users]

Checking the last login details for a single user with a quick PowerShell command is easy, as we’ve seen before. However, if you have a list of users and want to find out when they last logged in and save that information in a CSV file, follow these steps:

  • Before running the script, ensure you have installed the AzureADPreview module and connected to Entra ID using the Connect-AzureAD cmdlet.
  • Gather the UPN of Users in a text file. You can utilize Get-MsolUser to get user UPN information.
  • Don’t forget to update the $UPNlist variable with the path to your text file containing the User Principal Names (UPNs). For instance, you can set it like this:
$UPNlist = Get-Content <path_of_user_upn_text_file>
  • By default, the exported data is saved in a file named LastLogininfo.csv in the C:\temp directory. However, you can modify the script to store the report in a different location.
  • If a user has never logged in, the lastlogindate column in the report will display Never Logged In to indicate that no previous login activity has been recorded for that user.
  • Copy the Powershell code below and save it in a file with a .ps1 extension, for example, ExportLastlogin.ps1. Then, execute the script to Export the data.

ExportLastlogin.ps1

<#
.DESCRIPTION
    This script Export users Last Sign in date time from AzureAD.
    Copy the UPNs and provide the path of the text file in $UPNlist 
    variable.
    Author:  Jatin Makhija
    Site:    cloudinfra.net
    Version: 1.0.0
#>
$UPNlist = Get-Content C:\output\upn.txt
$object  = Foreach ($upn in $upnlist) {
  try {
      $signindata = Get-AzureADAuditSignInLogs -Filter "startsWith(userPrincipalName, '$upn')" -top 1
      if ($signindata -eq $Null)
          {
          [PSCustomobject]@{
             UserdisplayName = $upn
             LastLoginDate = "Never Logged in"
          }  
      }
      Else{
           [PSCustomobject]@{
             UserdisplayName = $signindata.UserDisplayName
             LastLoginDate = $signindata.CreatedDateTime
            }
      }
}
      Catch {
        Write-Error $_
      }
}
$object | Export-csv c:\temp\LastLogininfo.csv -NoTypeInformation
  • Here is an example of a report retrieved using the above script.
Export the Last Login Date/Time Information Using Powershell
Export the Last Login Date/Time Information Using Powershell

4. Export the Last Login Date/Time to CSV Using Powershell [for All Entra ID Users]

Earlier, we learned how to export the last login information for a list of Entra ID users into a text file. We will explore how to export the last login information for all Entra ID users using the PowerShell script below. Before running this script, please take note of the following key points:

  • Before running the script, ensure you have installed the AzureADPreview module and connected to Entra ID using the Connect-AzureAD cmdlet.
  • Install MSOnline Powershell module using Install-module -Name MSOnline.
  • Connect to MSOnline using Connect-MsolService cmdlet.
  • Exported data will be stored in C:\temp\LastLogininfo.csv file. You can change the location in the script if you want to save the report in a different location.
  • If the User has never logged on, the LastLoginDate column will show Never Logged In.
  • Copy the Powershell code below and save it in a file with a .ps1 extension, for example, ExportLastlogin.ps1. Then, execute the script to Export the date.

ExportLastlogin.ps1

<#
.DESCRIPTION
    This script Export users Last Sign in date time from AzureAD.
    Copy the UPNs and provide the path of the text file in $UPNlist 
    variable.
    Author:  Jatin Makhija
    Site:    cloudinfra.net
    Version: 1.0.0
#>
$allUsers = Get-MsolUser -all
$object  = Foreach ($upn in $allUsers.userprincipalname) {
  try {
      $signindata = Get-AzureADAuditSignInLogs -Filter "startsWith(userPrincipalName, '$upn')" -top 1
      if ($signindata -eq $Null)
          {
          [PSCustomobject]@{
             UserdisplayName = $upn
             LastLoginDate = "Never Logged in"
          }  
      }
      Else{
           [PSCustomobject]@{
             UserdisplayName = $signindata.UserDisplayName
             LastLoginDate = $signindata.CreatedDateTime
            }
      }
}
      Catch {
        Write-Error $_
      }
}
$object | Export-csv c:\temp\LastLogininfo.csv -NoTypeInformation

More Information

1. Get-AzureADAuditSignInLogs is not recognized

You might encounter an error message when retrieving a user’s last login information using the Get-AzureADAuditSignInLogs cmdlet or when executing a script that utilizes this cmdlet. The error message you may encounter is as follows:

Get-AzureADAuditSignInLogs : The term 'Get-AzureADAuditSignInLogs' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:1 char:1
+ Get-AzureADAuditSignInLogs
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-AzureADAuditSignInLogs:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The error can be resolved by following these key points and ensuring that each one is addressed:

  • To resolve the error, install the AzureADPreview PowerShell module on your device. If it’s not already installed, use the Install-Module -Name AzureADPreview command.
  • If you encounter any issues, try running the command as an administrator with the -AllowClobber and Force flags like this: Install-Module -Name AzureADPreview -AllowClobber -Force on a PowerShell console.
Get-AzureADAuditSignInLogs is not recognized
Get-AzureADAuditSignInLogs is not recognized
  • To verify whether the AzureADPreview PowerShell module has been successfully installed, run the following command: get-command *azureadaudit* to find out if Get-AzureADAuditSignInLogs cmdlet is available.
  • It’s important to note that even if the AzureADPreview module has been installed successfully, you can still encounter the same error message if you don’t have the necessary permissions to read Entra ID sign-in logs. The error message, Get-AzureADAuditSignInLogs is not recognized may persist due to insufficient permissions to access this specific feature.
  • You can try elevating your permissions to test and potentially resolve the issue. If possible, grant yourself global administrator rights and test if you still encounter the same error message when using the Get-AzureADAuditSignInLogs cmdlet. Often, this issue can be resolved by having the appropriate administrative privileges to access Entra ID sign-in logs.
Get-AzureADAuditSignInLogs is not recognized
Get-AzureADAuditSignInLogs is not recognized

Conclusion

In this blog post, we’ve covered exporting the last login information for Entra ID users into a CSV file. You can also list the last login information directly on the PowerShell console for a quick view by omitting the Export-CSV cmdlet from the script.

If you encounter any issues, please ensure you’ve connected to AzureAD and the MSOnline service before running the script.

Leave a Comment