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 Active directory (if the authentication provider is AD) using PowerShell.
PowerShell Script to Find the SharePoint user last login time:
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?
Solution: We can retrieve the user's last login time from Active directory (if the authentication provider is AD) using PowerShell.
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 $LogonTimeLets add some more error handling and find last logon time of all users of SharePoint.
PowerShell Script to Find the SharePoint user last login time:
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 Last Login time stamp. The above script pulls data from Active directory. So, data may be bit inconsistent - because if the user logon to any other systems like Exchange Server Email, AD will have that time stamp, doesn't matters if the user has logged on to SharePoint or not!
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
ReplyDelete