Finding last Logon time with PowerShell

I needed to find out last AD log-on time for a particular Active Directory user account on all our domain controllers. I already knew that it should not be particular difficult to come up with some PowerShell one-liner.

With some help aside by the Google, I finally came up with the statement that I liked and that is worthy of this note for my future reference:

PS>
PS>
PS> $username='alesk'
PS> Get-QADComputer -ComputerRole DomainController | foreach {(Get-QADUser -Service $_.Name -SamAccountName $username) | select Name, DisplayName, LastLogon, Path} | sort LastLogon
PS>

…and with the output similar to this one:

Name DisplayName LastLogon Path
---- ----------- --------- ----
alesk ales-k 07.08.2009 23:30:00 LDAP://acme-dc2.corp.com...
alesk ales-k 10.08.2009 11:21:57 LDAP://acme-dc1.corp.com...
alesk ales-k 10.08.2009 11:40:01 LDAP://acme-dc3.corp.com...
alesk ales-k 10.08.2009 15:20:25 LDAP://acme-dc4.corp.com...

The logic behind the script is simple:

1) get the list of all the DC’s from ActiveDirectory (Get-QADComputer -ComputerRole DomainController).

2) then query each domain controller (-Service $_Name) for the account passed as variable ($username) and then select the attributes that are needed with ith the select statement (use select * to examine the vast amount of attributes available for querying).

3) finally, I wanted the result to be sorted by LastLogon field.

Posted on 10.08.2009, in Scripting and tagged , . Bookmark the permalink. Comments Off on Finding last Logon time with PowerShell.

Comments are closed.