Last logon time

A question was left on the about section of my blog asking about a script that the reader had found. The script was supposed to return the last logon time for a user as found on each domain controller in the domain

Unfortunately there were a number of errors in the script.  This function will do the job

if (-not (Get-Module ActiveDirectory)){
  Import-Module ActiveDirectory
}            

function Get-ADUserLastLogon{
param(
[string]$userName
)            

Get-ADDomainController -Filter {Name -like "*"} |
foreach {
 $dc = $_.HostName             

 Get-ADUser -Identity $userName -Properties LastLogon -Server $dc |
 select Name,
 @{N="Last Logon"; E={[DateTime]::FromFileTime($($_.LastLogon))}},
 @{N="Domain Controller"; E={$dc}}               

}
}              

Get-ADUserLastLogon -UserName Richard

Get the domain controllers and pipe into foreach-object

The user information is retrieved from the domain controller using the –Server parameter to specify it. The select-object adds the domain controller name to the object and converts the AD time to something a bit more readable

Advertisement
This entry was posted in PowerShell and Active Directory. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s