Active Directory User Last Logon (PS Script)

This script was designed to answer the ever duanting question of: “When did a user last logon?” Since the attribute does not replicate to other domain controllers you are required to get the information from all domain controllers connnected to the domain. It uses command line arguments to pass user name and domain to be searched.

Using QAD we pull from every domain controller, then pull the user from every controller and pipe it into sort-object and then select-object to show just the most recent logon.

Script

$user = args[0] 
$domain = args[1] 
 
$domain = $domain.tolower() 
 
#Suppress Errors for DC's that have computer accounts but not connected to the domain 
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue 
$WarningPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue 
 
Switch($domain) 
{ 
    domain1 {$dom = "my.domain.com"} 
    domain2 {$dom = "another.domain.int"} 
    domain3 {$dom = "yet.another.domain.local"} 
} 
 
Connect-QADService -service $dom 
 
Get-QADComputer -ComputerRole DomainController -activity "Compiling Domain Controllers in $Domain" | % { 
$dc = $_.Name 
Get-QADUser -service $dc -samaccountname $User } | sort-object lastLogon -descending | select-object name, lastlogon -first 1 
Verified on the following platforms
Windows Server 2008 R2 Yes
Windows Server 2008 No
Windows Server 2003 No
Windows 7 No
Windows Vista No
Windows XP No
Windows 2000 No
This script is tested on these platforms.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.