I wanted to find all the old computer & user objects that haven't logged into the domain in awhile. With the native Microsoft Active Directory powershell module I thought this would be a simple task.
I wrote scripts easily enough that pulled this information out and dumped it all to a CSV file. I utilized the powershell cmdlets "Get-ADUser" & "Get-ADComputer" along with the attribute "LastLogonDate". I then realized this wouldn't work because the "LastLogonDate" attribute is per domain controller and not across the entire domain. So that would only work correctly if I had a single domain controller. I then found there are 2 other attributes in regards to logon time events. Those 2 are "lastLogon" & "lastLogonTimestamp". I did some research on the difference of these 2 and found out that "lastLogon" again is to a single domain controller that you are running the cmdlet against but just in a different format from "LastLogonDate". "lastLogonTimestamp" is the last time the user/computer logged into the domain at all. So I went with this one.
So I changed my script to utilize "lastLogonTimestamp". It ran fine but there was an issue. The format of the data of the "lastLogonTimestamp" is basically unreadable. It's just a long number. I did some research on the number and basically the number it gives us is Windows Epoch time. Which means the number it gives is the amount of time since Jan 1, 1601. So I needed my script to convert this number to a normal date format. It took a while to get it right but I wrote 2 scripts. One for Computer Objects and One for User Objects. Each script just generates a CSV file that can be imported into Excel for correct formatting. Before I get to the scripts I want to make it noted that even the "lastLogonTimestamp" attribute isn't exact. It can be off by around 9 to 14 days.
Here is the script for computer objects:
#The 90 is the number of days from today since the Computer has last logged into the domain. Change it to whatever number you want.
$then = (Get-Date).AddDays(-90)
$OLD = Get-ADComputer -Property Name,lastLogontimestamp,OperatingSystem -Filter {lastLogontimestamp -lt $then}
foreach($svr In $OLD)
{
$mydatetime = $svr.lastlogontimestamp
$time = [datetime]::FromFileTime($mydatetime)
$svr.Name + "," + $svr.OperatingSystem + "," + $time | Out-File OldAdComputerObjects.csv -append
}
---------------------------
Here is the script for user objects:
$then = (Get-Date).AddDays(-90) #The 90 is the number of days from today since the user has last logged into the domain.
$OldUser = Get-ADUser -Property Name,SamAccountName,lastLogontimestamp -Filter {lastLogontimestamp -lt $then}
foreach($User In $OldUser)
{
$mydatetime = $User.lastlogontimestamp
$time = [datetime]::FromFileTime($mydatetime)
$User.Name + "," + $User.SamAccountName + "," + $time | Out-File OldAdUserObjects.csv -append
}