Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

How to get last logon of user on Domain Controllers using Powershell

25 November,2021 by Tom Collins

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

 


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to get last logon of user on Domain Controllers using Powershell


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer