August 12, 2013

Get Users Last Logon Time and Date using PowerShell

A question we sometimes need, but can't get from SharePoint is users last logon time. Usually you have an environment where a user signs in to the network and is authorized to access the company intranet without further password requirements in a single sign on environment. But the information isn't stored in SharePoint, so we can't get it from there.

However, the information is stored in Active Directory, and by importing it, you can get the information when all of your users where last active (logon) on your domain.

# Load the SharePoint cmdlets
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'} 
if ($snapin -eq $null
{    
    Write-Host "Loading SharePoint Powershell Snapin"    
    Add-PSSnapin "Microsoft.SharePoint.Powershell"  -EA SilentlyContinue
}

# Import ActiveDirectory cmdlets
Import-Module ActiveDirectory

# Here's the function that will return the last logon date and time
function Get-ADUserLastLogon([string]$userName)
{
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $time = 0
  foreach($dc in $dcs)
  { 
    $hostname = $dc.HostName
    $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon 
    if($user.LastLogon -gt $time
    {
      $time = $user.LastLogon
    }
  }
  $dt = [DateTime]::FromFileTime($time)
  Write-Host $username "last logged on at:" $dt 
}

# Get the user profiles
$site = Get-SPSite "https://intranet.company.com/"
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context
$profiles = $profileManager.GetEnumerator()

# Iterate all profiles and grab the users last logon date time and write to console
foreach($user in $profiles)
{
     Get-ADUserLastLogon -UserName $user["UserName"]
}

Reference: Determining a User's Last Logon Time

2 comments:

  1. not accurate with sharepoint - does not show matching activity of users logging directly in to sharepoint off the network, not sure why. This is likely true of any other externally facing app.

    ReplyDelete
    Replies
    1. True! This script checks last logon time to the Active Directory, and not SharePoint itself.

      Delete