GEt users last logon time

gd6627
gd6627 used Ask the Experts™
on
I need a Powershell script that will get me the last logon time of a user
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chris DentPowerShell Developer
Top Expert 2010

Commented:
If you base it on lastLogonTimeStamp you can use the lastLogondate property.
Get-ADUser -Identity username -Properties lastLogonDate

Open in new window

Did you need the more accurate lastLogon value (which isn't replicated)?

Commented:
No sense in reinventing the wheel:

https://technet.microsoft.com/en-us/library/dd378867(v=ws.10).aspx

Import-Module ActiveDirectory

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-ADUserLastLogon -UserName SaraDavis

Open in new window

Technical Specialist
Awarded 2017
Distinguished Expert 2018
Commented:
Import-Module ActiveDirectory
$SearchBase = "OU=User Accounts,DC=Dundermifflin,DC=com"
Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName | ForEach-Object {
	"Processing $_ ..." | Write-Host
	Get-ADUser -Server $_ -SearchBase $SearchBase -Filter {Enabled -eq $true} -Properties Name, LastLogon |
		Select-Object Name, SamAccountName, @{n='LastLogon'; e={[DateTime]::FromFileTime($_.LastLogon)}}
} | Group-Object -Property SamAccountName | ForEach-Object {
	$_.Group | Sort-Object -Property LastLogon -Descending | Select-Object -First 1
} | Sort-Object -Property LastLogon, SamAccountName |
	Export-CSV -Path "Path" -NoTypeInformation

Open in new window

from https://www.experts-exchange.com/questions/29005951/Powershell-Get-lastLogon.html

Author

Commented:
Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial