I came across the following script that almost meets my requirement. It queries all the domain controllers and gets the recent logged in time and date.
What i am trying to do is run it against AD i.e. using "-Searchbase"
parameter get i want to be able to get the results in a csv format containing samaaccountnme, Searchbase location and lastlogon time.
It is essentail for the auditing purposes.
Import-Module ActiveDirectory
function Get-ADUserLastLogon([string]$userName)
{
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Server $hostname -Properties lastLogon
if($user.LastLogon -gt $time)
{
$time = $user.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
Write-Host $username "last logged on at:" $dt }
Get-ADUserLastLogon -UserName testuser
I even tried changing the following line that i thought would fixes it but no luck.
$user = Get-ADUser -Filter * -Properties * -Searchbase "OU=Staff,DC=Home,DC=ac,DC=uk" | Get-ADObject -Server $hostname -Properties lastLogon
Get-AduserLastLogon $Username
Can someone please help please.
Here is an example of how to get most recent lastLogon attribute for users on all DCs: