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.
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.
Parameters
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 srvdc1.alexandreviot.net
The script also creates the CSV file into the folder where it was executed.
Last Logon Powershell script
Below the Powershell script:
param( [parameter(Mandatory=$true)][String]$SourceOUName, [parameter(Mandatory=$true)][String]$SourceServer ) #LDAP Search $Searcher = New-Object DirectoryServices.DirectorySearcher $Searcher.Filter = "(&(objectClass=computer))" $Searcher.SearchRoot = "LDAP://$SourceServer/$SourceOUName" $SourceAllComputers=$Searcher.FindAll() #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 $Computer=[ADSI]$computerADSI.path #Get computer information $name= [string]$Computer.name $os=[string]$Computer.operatingsystem #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) { $SourceLastLog="DISABLED" }else{ #Convert the timestamp into date format $tm=$Computer.ConvertLargeIntegerToInt64($Computer.LastLogonTimeStamp[0]) $SourceLastLog=([datetime]::fromfiletime($tm)).ToString("dd.MM.yyyy HH:mm:ss") } }else{ $SourceLastLog="NULL" } #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 } |