Guest User

Powershell LastLoginTimeStampForUser

a guest
Aug 2nd, 2013
820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ##############################################################################
  2. #Powershell 2,3
  3. #Script to find the last login time of a user by comparing last login times
  4. #     recorded on each domain controler and selecting the last one.
  5. #
  6. ##############################################################################
  7. #     by: ki01s
  8. #     Date: 7/3/13
  9. #    
  10. ##############################################################################
  11. #Import the module to access Active Directory
  12. Import-Module ActiveDirectory
  13.  
  14. #ask for a username to look up
  15. $LoginName = Read-Host "What user would you like to look up?"
  16.  
  17. #Create function to use in other scripts
  18. function Get-ADUserLastLogon([string]$userName)
  19. {
  20.  
  21.  #get full list of domain controllers in current domain
  22.   $dcs = Get-ADDomainController -Filter {Name -like "*"}
  23.   $time = 0
  24.  
  25.  #Query each domain controler to find the last date and time user logged in.
  26.   foreach($dc in $dcs)
  27.   {
  28.  
  29.     $hostname = $dc.HostName
  30.     $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon
  31.  
  32.     #compare times from each DC to determine last login time
  33.     if($user.LastLogon -gt $time)
  34.     {
  35.       $time = $user.LastLogon
  36.     }
  37.   }
  38.   $dt = [DateTime]::FromFileTime($time)
  39.  
  40.   #display the name and time of last login.
  41.   Write-Host $username "last logged on at:" $dt }
  42.  
  43. Get-ADUserLastLogon -UserName $LoginName
  44. ##Unhash the two lines below, if running script from command line to pause script and wait for keypress before closing window.
  45. #Write-Host "Press any key to continue ..."
  46. #$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Advertisement
Add Comment
Please, Sign In to add comment