Get-AzureADAuditSignInLogs – Find Sign In Logs for Last 30 Days with PowerShell. Since its inception more than 10 years ago, PowerShell’s command line interface (CLI) has proven to be a vital tool for managing local and remote Windows, macOS, and Linux systems. One of its vital uses in server administration is finding the sign in logs of various users by administrators. PowerShell enables administrators to do so efficiently, and this article is a detailed analysis of the full steps necessary to find sign-in logs by using PowerShell. But first…
Why would Administrators need Sign In information?
There are a couple of reasons why a server admin might want to know who logged in on the server. Here are a few:
- By getting the sign in information, the administrators check the login behaviour of the users.
- With the login history, the admins can whether or not the users’ login and logout activities are normal and are helpful in detecting suspicious activity on the server.
- Login history also helps admins to create better management strategies for the server. For example, network administrators know when traffic is high or low and from where, so they better allocate bandwidth accordingly.
- Using PowerShell scripts, the admins find stale or inactive users on the server and take appropriate actions as needed. This helps in reducing inorganic load from the server by eliminating inactive or non interactive users off the server. As a result, only valid, genuine, active, and organic users stay on the server, which helps in the best utilization of server’s resources.
Using PowerShell to obtain Azure AD Sign In Logs
We use the Get-AzureADAuditSignInLogs command to do so.
The syntax of this command is as follows:
Get-AzureADAuditSignInLogs [-All <Boolean>] [-Top <Int32>] [-Filter <String>] [<CommonParameters>]
But first, before using this command, here are the steps that you need to follow:
1. Install AzureADPreview
Install the module called “AzureADPreview,” before you fetch the data from Windows PowerShell. For installation, launch Windows PowerShell and run the following command:
Install-Module AzureADPreview –AllowClobber
2. Connect To Azure Tenant
The installation should hardly take a few seconds. Once the installation is successful, you need to use that newly installed Azure AD Preview module to connect with your Azure tenant. To do this, please run the following command:
AzureADPreview\Connect-AzureAD
Once this is done, you are finally ready to fetch the login records.
Getting Sign In Data of the last 10 Logins
The command below helps you to fetch the data of last 10 logins.
Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq 'maxbak@woshub.onmicrosoft.com'" -Top 10 | select CreatedDateTime, UserPrincipalName, IsInteractive, AppDisplayName, IpAddress, TokenIssuerType, @{Name = 'DeviceOS'; Expression = {$_.DeviceDetail.OperatingSystem}}|ft
Please remember that this command can be changed so you fetch records of last ‘n’ number of users. To do that, please notice “-Top 10” in the code above. Simply replace “10” with the number of last ‘n’ users whose data you wish to fetch.
Please note the code snippet after “select”, which is followed by the attributes that you want to fetch from the Active Directory. Add or remove attributes in the code snippet and Windows PowerShell works with the input attributes. Accuracy is important as misspelled or mismatched cases in the attribute names result in an error.
Fetching Data of Azure AD Log ins for Last ‘30’ Days
Apart from being able to fetch ‘n’ number of users, you can also write a PowerShell script to fetch the records of ‘n’ number of days. In our case, this gets the data of the last 30 days. To do so, please execute this PowerShell script code below:
$SetDate = (Get-Date).AddDays(-30);
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$array = Get-AzureADAuditSignInLogs -Filter "createdDateTime gt $SetDate" | select userDisplayName, userPrincipalName, appDisplayName, ipAddress, clientAppUsed, @{Name = 'DeviceOS'; Expression = {$_.DeviceDetail.OperatingSystem}},@{Name = 'Location'; Expression = {$_.Location.City}}
$array | Export-Csv "C:\PS\AzureUserSigninLogs.csv" –NoTypeInformation
The above code generates the data for the last 30 days. However, if you want, you also fetch the data for any ‘n’ number of days. To do so, you’ll need to alter the. AddDays() command in the first line. Please pass the argument “-n” (n refers to your select number of days) instead of “-30” and leave the entire code snippet unchanged.
It’s also worth noting that the above code is intended to export the data as a.csv file, which you modify as needed. To make a change, edit the last line, “array | Export-Csv.” Simply replace “CSV“ with the extension of your preferred export file type to alter the type of the export file. Finally, be sure to update the file’s extension at the end, where the recipient’s address is indicated.
Obtaining Sign in Records for Users and Applications
The above “Get-AzureADAuditSignInLogs” PowerShell scripts output the data into a csv file or an alternative file format. Suppose we would just like PowerShell to analyse, process and then populate these records in a PowerShell object? If so, then we need to run this code:
# Fetches the last month's Azure Active Directory sign-in data
CLS; $StartDate = (Get-Date).AddDays(-30); $StartDate = Get-Date($StartDate) -format yyyy-MM-dd
Write-Host "Fetching data from Azure Active Directory..."
$Records = Get-AzureADAuditSignInLogs -Filter "createdDateTime gt $StartDate" -all:$True
$Report = [System.Collections.Generic.List[Object]]::new()
ForEach ($Rec in $Records) {
Switch ($Rec.Status.ErrorCode) {
"0" {$Status = "Success"}
default {$Status = $Rec.Status.FailureReason}
}
$ReportLine = [PSCustomObject] @{
TimeStamp = Get-Date($Rec.CreatedDateTime) -format g
User = $Rec.UserPrincipalName
Name = $Rec.UserDisplayName
IPAddress = $Rec.IpAddress
ClientApp = $Rec.ClientAppUsed
Device = $Rec.DeviceDetail.OperatingSystem
Location = $Rec.Location.City + ", " + $Rec.Location.State + ", " + $Rec.Location.CountryOrRegion
Appname = $Rec.AppDisplayName
Resource = $Rec.ResourceDisplayName
Status = $Status
Correlation = $Rec.CorrelationId
Interactive = $Rec.IsInteractive }
$Report.Add($ReportLine) }
Write-Host $Report.Count "sign-in audit records processed."
This code above gives a much more detailed output that’s already been processed which is very helpful as will be shown below.
Getting Sign In Data for Applications
Let’s use the processed sign in data that we got to determine which applications are the most used. To do so, we execute this code:
$Report | Group AppName | Sort Count -Descending | Format-Table Count, Name
After running the above code, PowerShell gives me the following output:
499 Microsoft Teams Web Client
200 Microsoft Exchange REST API Based Powershell
80 Azure Active Directory PowerShell
79 Office365 Shell WCSS-Client
64 SharePoint Online Web Client Extensibility
As an administrator, I now use this information to identify my most frequently used Office applications and how they function. This is one of the advantages of using the Get-AzureADAuditSignInLogs cmdlet. It is a great tool for analyzing data.
For, example, based on this data, Teams is the most heavily used application. A reason for this could be the fact that Teams signs into many different resources when it starts up, including SharePoint Online, Exchange Online, and the Skype presence service. Microsoft Exchange REST based cmdlets are also heavily used. This is mainly due to the module constantly reconnecting to Exchange Online, often during a session.
Getting the Sign In Location Data
Let’s also use the above data to find out where users sign in from:
$Report | Group Location|Sort Count -Descending | Format-Table Count, Name
Output:
300 Togrenda, Akershus, NO
200 Washington, Virginia, US
167 Kleinpestitz/Mockritz, Sachsen, DE
89 Oxford, Oxfordshire, GB
70 Sofiya, Sofiya-Grad, BG
Run Reports on your Azure AD Audit Sign-Ins with InfraSOS
Try us out for Free, Access to all features. – 200+ AD Report templates Available. Easily customise your own AD reports.
Obtain Sign In Logs from a Specific Location
The output above contains grouped records for various locations. To get the sign in records of a specific record, (for example Washington) you need to run this code:
#Obtains sign-in records from Washington
Get-AzureADAuditSignInLogs -Filter "location/city eq 'Virginia' and location/state eq 'Washington' and location/countryOrRegion eq 'US'"
Obtaining Sign in Logs based on Specific Parameters
Also get sign in records for individual users by filtering based on various parameters.
The code below finds all sign-in records for ‘Jean Niyomugabo.’
Get-AzureADAuditSignInLogs -Filter "userDisplayName eq 'Jean Niyomugabo '"
The code below filters the records based on her username ‘JNiyomugabo@Contoso.com’
Get-AzureADAuditSignInLogs -Filter "startsWith(userPrincipalName,'JNiyomugabo@Contoso.com')"
The code below filters the records based on her app ID:
Get-AzureADAuditSignInLogs -Filter "appId eq 'de8bc8b5-d9f9-48b1-a8ad-b748da725064'"
The code below filters the records based on the app display name:
Get-AzureADAuditSignInLogs -Filter "appDisplayName eq 'myApp'"
Obtaining All Login Records with a Certain Status
Sign in success (eq 0) and failure (ne 0) logsare obtained using the following commands.
Get-AzureADAuditSignInLogs -Filter "status/errorCode eq 0" -All $true
Get-AzureADAuditSignInLogs -Filter "status/errorCode ne 0"
Finding the Last Login date of a given user for Active Directory
On premise Active Directory PowerShell also gives you the ability to find the last login date of a given user using Windows PowerShell. Here is the step by step guide of doing so for Active Directory last logins:
- First you need to log into the domain controller where the user is located.
- Then finally, use the command below in Windows PowerShell to get the list of all the users with their last login timestamp.
Get-ADUser -filter * -Properties "LastLogonDate" | select name, LastLogonDate
This command retrieves all sign in logs received on or after 20/3/2022.
Using the Azure portal to get Azure AD Sign in Data
Also get sign in details from the Azure Portal. To get similar sign logs that you’d get by using the Get command, you need to follow the following steps:
- Sign into the Azure portal.
2. Find Azure Active Directory in the search bar and choose it from the search results.
Sign in logs can be accessed from the Azure Active Directory’s left hand menu. Go to the User Sig -ins (Interactive) section. You then filter your results to narrow them down to the last 7 days, 24 hours, etc.
Thank you for reading Get-AzureADAuditSignInLogs – Find Sign In Logs for Last 30 Days with PowerShell. We shall conclude the article now.
Get-AzureADAuditSignInLogs - Find Sign In Logs for Last 30 Days with PowerShell (Conclusion)
In this article, you saw a list of methods and a step by step guide of getting the login data for the last 30 days as well as other useful PowerShell commands that are useful for server management. The Get-AzureADAuditSignInLogs cmdlet is a good tool for analysing user data, resource usage and identifying inactivity.
However, it is important to note that while you can get the login data of users it’s not always feasible to take actions against inactive users. This is because there could be several valid reasons for the user’s inactivity. Moreover, it’s important to note that removing a user or restricting a user from using the server’s resources isn’t always an easy task. Therefore, as an administrator, it is a good server management practice for you to take this action only when absolutely necessary.
Try InfraSOS for FREE
Invite your team and explore InfraSOS features for free
- Free 15-Days Trial
- Easy Setup
- Full Access to Enterprise Plan
Related posts:
- Check Azure AD Audit Logs for User Sign-Ins (Success Failures)
- Windows Server Patch Management: How to Keep Windows Server Secure & Up-to-Date
- Analyze Azure AD Security Logs: Audit & Monitor Azure AD Activity
- Automating Azure AD Auditing PowerShell: Simplifying Log Analysis
- How to Use NSLookup Command on Windows (Examples)
Comments (2)
Daniel Usrey
June 19, 2023Even after I got the AzureADPreview module to load I can now use the tab feature to load the Get-AzureADAuditSignInLogs. However, when I run it I get this message “Get-AzureADAuditSignInLogs : The term ‘Get-AzureADAuditSignInLogs’ is not recognized as the name of a cmdlet, function, script file, or operable program.”
William Mckenzie
August 2, 2023Im trying to filter connections from the last 24 hours as well as ones with only a specific email domain from outside the Uk,
I can filter the email domain and location easy, but when I add the time It causes problems,
the Filter -Filter “location/countryOrRegion ne ‘GB’ and contains(userPrincipalName,’@email.com’)” works but whenever I add the date in as well it doesnt