Monday, January 11, 2016

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.

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
Lets 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!



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!


You might also like:

Related Posts Plugin for WordPress, Blogger...