Find the Last Login Time of a SharePoint User from AD with PowerShell
Requirement: Find the last login time of all SharePoint users of the farm to find out inactive users.
Solution: We can retrieve the user’s last login time from the Active directory (if the authentication provider is AD) using PowerShell. In this blog post, we will show you how to find the last login time of a SharePoint user.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
$UserAccount="vani"
$User = Get-ADUser -Filter {SamAccountName -like $UserAccount} | Get-ADObject -Properties lastLogon
$LogonTime=[DateTime]::FromFileTime($User.LastLogon)
Write-host $LogonTime
Let’s add some more error handling and find the last login time of all users of SharePoint.
PowerShell Script to Find the SharePoint user last login time:
Let’s use the combination of SharePoint and Active Directory PowerShell modules to find out the last login time of all the users.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
#Custom Function Get the Last Logon Time of the User from AD
Function Get-ADUserLastLoginTime($UserAccount)
{
Try {
#Set the Error Action
$ErrorActionPreference = "Stop"
$User = Get-ADUser -Filter {SamAccountName -like $UserAccount} | Get-ADObject -Properties lastLogon
if($user.LastLogon)
{
return([DateTime]::FromFileTime($User.LastLogon))
}
else
{
return "Not Found!"
}
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
}
finally {
#Reset the Error Action to Default
$ErrorActionPreference = "Continue"
}
}
#Get All User Profiles
$SiteURL="https://intranet.crescent.com"
$ServiceContext = Get-SPServiceContext -site $SiteURL
$UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
#Get All User Profiles
$UserProfilesColl = $UserProfileManager.GetEnumerator()
Foreach($UserProfile in $UserProfilesColl)
{
$UserAccount=$UserProfile["UserName"]
$LogonTime = Get-ADUserLastLoginTime -UserAccount $UserAccount
Write-host "Last Logon Time of the User $UserAccount is $LogonTime"
}
Please note, SharePoint doesn’t store the Last Login time stamp. The above script pulls data from the Active directory. So, data may be a bit inconsistent – because if the user logon to any other systems like Exchange Server Email, AD will have that timestamp, doesn’t matter if the user has logged on to SharePoint or not! Here is my another post on How to Get the Last Sign-in Timestamp of a user from Azure AD for SharePoint Online?
However, If you parse IIS Logs of the SharePoint web application using Log parser, you can find the particular user’s activity: How to use Log Parser with SharePoint?
can we do that in Rest Api or CSOM