Last logon time with a script

Just for completeness I decided to look at the same problem using a script.  This is more complex.

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

$root = [ADSI]""
$search = [adsisearcher]$root
$search.Filter = "(&(objectclass=user)(objectcategory=user)(cn=$username))"
$search.SizeLimit = 3000
$results = $search.FindOne()            

foreach ($result in $results){
    $dn = $result.Properties.distinguishedname
}            

#$dn            

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() |
select -ExpandProperty DomainControllers |
foreach {
 $dc = $_.Name             

 [adsi]"LDAP://$dc/$dn"  |
 select @{N="Name"; E={$($_.Name)}},
 @{N="Last Logon"; E={([DateTime]$_.ConvertLargeIntegerToInt64($_.lastlogon.value)).AddYears(1600)}},
 @{N="Domain Controller"; E={$dc}}               

}
}              

Get-SCADUserLastLogon -UserName Richard

We need the distinguished name but we only have the name – time to search through AD for our user & pick off the distinguished name. We then get the domain controllers as before and loop through them.

For each domain controller we get the directory entry using [adsi] but notice that we put the domain controller into the LDAP string – this pulls the data from the specified domain controller. We can select the Name, last logon and domain controller. The calculation for converting last logon is different as we need to add 1600 years to get the right result!

As far as I am aware we can’t change which domain controller the AD provider points to so can’t do this type of processing

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