This Powershell script will iterate through all available Domain Controllers associated with Active Directory . It will record the last logon time on the specific Domain Controllers.
The script takes as an input parameter the id of the user .
In a previous post I outlined How to get all Domain Controllers in Active Directory Forest with Powershell . This script uses similar techniques , but with the added step of using the Get-ADUser cmdlet to check the user against the specific Domain Controllers.
The $resultlogonhistory=@() is a variable starting an array. In Powershell , @() means array. The process keeps adding content to the array .
Once the the process iterates through every Domain Controller , the array is exported to a CSV file - using the Export-CSV cmdlet.
A colleague of mine gave me the script , which I've used with success. Whoever else has contributed to this script - thanks you.
$userlogonname='an_id' $outputfile='c:\lastlogon.csv' $logonhistory=@() Import-Module ActiveDirectory $DCs=(Get-ADDomainController -Filter *).Name foreach ($DC in $DCs) { Try { $aduser=Get-ADUser $userlogonname -Server $DC -Properties lastlogon -ErrorAction Stop $logonhistory +=New-Object -TypeName PSObject -Property ([ordered]@{ 'USR' = $userlogonname 'DomainCont' = $dc 'LastLogon' = [datetime]::FromFileTime($aduser.'lastLogon') }) } Catch { Write-host "Cannot connect DC $($dc)!" } } $logonhistory|Export-CSV -path $outputfile -NoTypeInformation -Delimiter "," -Encoding UTF8
Read more on querying Active Directory with Powershell
How to extract Active Directory users with Get-ADGroup and Get-ADGroupMember
How to find Active Directory groups with Get-ADGroup search filter
How to get all Domain Controllers in Active Directory Forest with Powershell
How to find Active Directory users with Get-ADUser search filter