Active Directory 2012

Active Directory – Get Last logon using Powershell

During an Active Directory migration, I needed to do an inventory of the computers to migrate. Because some computers do not exist anymore but not removed from Active Directory. I created a Powershell script based on the Last Logon Timestamp property.

CSV file from the script

CSV file from the script

This powershell script creates a CSV file with the computer name, the last logon property and the operating system. Some domains were based on Windows Server 2003 or 2008, I could not use Active Directory commandlets, so I used the LDAP Search.


This script is quite simple with two parameters:

  • SourceOUName: the Distinguished name of the target OU.
  • SourceServer: Source Domain Controller.

If you want to target all computers in the domain: .\AD_GetLastLogon.ps1 -SourceOUName “DC=alexandreviot,DC=net” -SourceServer

Execute Last Logon script

Execute Last Logon script

The script also creates the CSV file into the folder where it was executed.

Last Logon Powershell script

Below the Powershell script:

 #LDAP Search
 $Searcher = New-Object DirectoryServices.DirectorySearcher
 $Searcher.Filter = "(&(objectClass=computer))"
 $Searcher.SearchRoot = "LDAP://$SourceServer/$SourceOUName"
 #Display the number of computer
 $count= $SourceAllComputers | Measure-Object  
 Write-Host   $count.count
 #Get the date in Switzerland format
 $date= Get-date -Format "dd.MM.yyyy"
 #Create the CSV file with header
 echo "Name,LastLogon,OS" | out-file -FilePath "$SourceOUName-$date.txt" -Append 
foreach($computerADSI in $SourceAllComputers)
	#Get the computer object
    #Get computer information
    $name= [string]$
    #If the timestamp is not null
    if ($Computer.LastLogonTimeStamp[0] -notlike "") 
		#Check if the computer is disabled
        if ($Computer.Properties.useraccountcontrol -eq 4098 -OR $Computer.Properties.useraccountcontrol -eq 4130)
		#Convert the timestamp into date format
        $SourceLastLog=([datetime]::fromfiletime($tm)).ToString("dd.MM.yyyy HH:mm:ss")
   #Display information on Powershell console   
   Write-Host $name","$SourceLastLog","$os
   #Save information into CSV file
   echo $name","$SourceLastLog","$os | out-file -FilePath "$SourceOUName-$date.txt" -Append

Leave a Reply

Your email address will not be published. Required fields are marked *