Get-OldComputers
Getting a List of Old Computers in Active Directory (AD)
In the code below, I (essentially) define an “old computer” as one that hasn’t changed it’s AD password or logged-in to AD in the last 12 - 18 months. Change the code to match your definition.
If you don’t want to keep entering your AD Domain every script execution, I’d change the Domain parameter too.
If you allow delegated admins in your Domain, or if you just want to concentrate on a specific organization unit (OU), you can supply the OU parameter in standard LDAP distinguishedName format.
If you are unfamiliar with using the .Net DataSet and DataTable for an in-memory database, you may find some of this code instructive. Certainly, using the DataTable’s Select() member function was far faster than using a PowerShell Where-Object or a Contains. By the way, putting the [void] in front of many of the actions in the code prevents it from emitting whatever return value/object that action normally returns (I didn’t want the return value anyway).
<#
.SYNOPSIS
Generate a report on computers that haven't changed their passwords or logged in the last 12 - 18 months.
.DESCRIPTION
In an effort not to require the AD module, this code uses DirectoryServices.
The code uses your current AD identity to query AD.
ASSUMPTIONS:
- You are using a Domain joined machine in the Domain you want to query
- You are logged into the Domain you want to query with proper credentials
- The dsquery.exe EXE is in your path
- If a computer has logged in recently and pwdLastSet is out of date, they must have some
reason not to change their password
.PARAMETER Domain
Defaults to your.domain (TODO: change it!)
.PARAMETER OU
The search root instead of the top of the directory
.PARAMETER IncludeBitlocker
If you have security rights to view Bitlocker information in your Domain, you can use this switch.
Otherwise, it will not generate an error and return the computer object data without bitlocker info.
.EXAMPLE
Get-OldComputers.ps1 | Export-Csv -NotypeInformation -Encoding utf8 -Path .\computers.csv
Get-OldComputers.ps1 | Out-GridView
.INPUTS
None
.OUTPUTS
An array of DataRow objects that you can export to a CSV or whatever you want.
.LINK
None
.NOTES
Ver Date Who What
--- ---- --- ----
1.0 2024-02-14 Ray Initial
1.1 2024-02-15 Ray Added BitLocker and in-memory dataset/datatable
1.2 2024-02-15 Ray Modified documentation
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string]$Domain='your.domain',
[Parameter(Mandatory=$false,HelpMessage='Enter something like: *OU=sub_ou,OU=parent_ou,DC=your,DC=domain')]
[string]$OU='',
[Parameter(Mandatory=$false,HelpMessage='Add this switch if you have security rights and wish to know')]
[switch]$IncludeBitlocker
)
Add-Type -AssemblyName System.DirectoryServices
Add-Type -AssemblyName System.Data
function GetBitLockerInfo {
# find all the bitlocker records
[string]$BitlockerFilter = '(&(&(objectClass=msFVE-RecoveryInformation)' +
'(msFVE-RecoveryPassword=*)))'
try {
$script:searcher.Filter = $BitlockerFilter
$script:searcher.SearchRoot = ''
$script:searcher.PropertiesToLoad.Clear()
# The msDS-ParentDistName contains the owner computer's distinguishedName
[void]$script:searcher.PropertiesToLoad.Add('msDS-ParentDistName')
[System.DirectoryServices.SearchResultCollection]$bits = $script:searcher.FindAll()
if ($null -ne $bits -and $bits.Count -gt 0) {
# Many computers have more than one bitlocker key.
# We only need to know if they have one or not.
[string]$select = [string]::Empty
foreach ($b in $bits) {
$select = "distinguishedName = '"
# The data may contain a "'" in it--replace it just in case.
# Since the AD query might contain several objects relating to the same computer
# I created this select query to ignore duplicates.
# TODO: Change this if you want to evaluate the bitlocker keys in more detail
$select += $b.Properties.Item('msds-parentdistname')[0].ToString().Replace("'","''")
$select += "' AND hasbitlocker = FALSE"
$row = $script:ds.Tables[$script:tbl].Select($select)
# Since the distinguishedName is the primary key (and unique), we'll never have more than one record
if ($row.Count -eq 1) {
$row.BeginEdit()
$row.Item(0).hasbitlocker = $true
$row.EndEdit()
}
}
}
else {
Write-Warning 'No BitLocker data found. Do you have permission to read it?'
}
}
catch {
throw
}
finally {
if ($bits) {
$bits.Dispose()
}
}
}
New-Variable -Name PAGE_SIZE -Value 100 -Option Constant
[string[]]$PropertiesToLoad = @('distinguishedName','lastLogonTimeStamp','name','operatingSystem','pwdLastSet','sAMAccountName','whenCreated')
[datetime]$Jan1970 = Get-Date -Year 1970 -Month 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
[datetime]$Midnight = Get-Date -Hour 0 -Minute 0 -Second 0 -Millisecond 0
[datetime]$TwelveMonthsAgo = $Midnight.AddMonths(-12)
[datetime]$EightteenMonthsAgo = $Midnight.AddMonths(-18)
# TODO: These are arbitrary time limits. Change them to meet your requirements
# Find all enabled computers with a password last set and a lastlogontimestamp
# >= 12 months ago and less then 18 months ago
[string]$TwelveMonthFilter = "(&" +
"(objectCategory=Computer)(objectClass=Computer)" +
"(!useraccountcontrol:1.2.840.113556.1.4.803:=2)" +
"(&" +
"(pwdLastSet<=$($TwelveMonthsAgo.ToFileTime()))" +
"(pwdLastSet>=$($EightteenMonthsAgo.AddSeconds(-1).ToFileTime()))" +
")" +
"(&" +
"(lastLogonTimeStamp<=$($TwelveMonthsAgo.ToFileTime()))" +
"(lastLogonTimeStamp>=$($EightteenMonthsAgo.AddSeconds(-1).ToFileTime()))" +
")" +
")"
# connect to the domain and create a directory searcher
$RootDE = New-Object System.DirectoryServices.DirectoryEntry -ArgumentList "LDAP://$($Domain)"
$script:searcher = New-Object System.DirectoryServices.DirectorySearcher -ArgumentList $RootDE
try {
$script:searcher.Filter = $TwelveMonthFilter
$script:searcher.PageSize = $PAGE_SIZE
$script:searcher.SearchScope = 'Subtree' # search all sub OUs
$script:searcher.PropertiesToLoad.AddRange($PropertiesToLoad) # we only need a few properties
if ($OU -ne '') {
$dsq = dsquery.exe ou "$($OU)" -scope base
if ($null -eq $dsq) {
Write-Error "I could not find the OU '($OU)' supplied in the '$($Domain) Domain"
throw 'OU not found!'
}
else {
$script:searcher.SearchRoot = $OU
}
}
[System.DirectoryServices.SearchResultCollection]$SearchResult = $script:searcher.FindAll()
if ($SearchResult) {
[string]$tbl = 'comps'
$script:ds = New-Object System.Data.DataSet
[void]$script:ds.Tables.Add($tbl)
[void]$script:ds.Tables[$tbl].Columns.Add('distinguishedName', [string])
[void]$script:ds.Tables[$tbl].Columns.Add('lastLogonTimeStamp', [datetime])
[void]$script:ds.Tables[$tbl].Columns.Add('name', [string])
[void]$script:ds.Tables[$tbl].Columns.Add('operatingSystem', [string])
[void]$script:ds.Tables[$tbl].Columns.Add('ou', [string])
[void]$script:ds.Tables[$tbl].Columns.Add('pwdLastSet', [datetime])
[void]$script:ds.Tables[$tbl].Columns.Add('sAMAccountName', [string])
[void]$script:ds.Tables[$tbl].Columns.Add('whenCreated', [datetime])
[void]$script:ds.Tables[$tbl].Columns.Add('hasbitlocker', [bool])
$script:ds.Tables[$tbl].Columns['hasbitlocker'].DefaultValue = $false
$script:ds.Tables[$tbl].PrimaryKey = $script:ds.Tables[$tbl].Columns['distinguishedName']
Write-Information "Number of Computer Objects to possibly disable: $($SearchResult.Count)"
[int16]$si = -1
$o = New-Object PSObject -Property @{distinguishedName='';lastLogonTimeStamp=$Jan1970;name='';
operatingSystem='';ou='';pwdLastSet=$Jan1970;sAMAccountName='';whenCreated=$Jan1970;}
foreach ($result in $SearchResult) {
$o.distinguishedName = ''
$o.lastLogonTimeStamp = $Jan1970
$o.name = ''
$o.operatingSystem = ''
$o.ou = ''
$o.pwdLastSet = $Jan1970
$o.sAMAccountName = ''
$o.whenCreated = $Jan1970
$o.distinguishedName = $result.Properties.distinguishedname[0]
if ($null -ne $result.Properties.Item('lastlogontimestamp')) {
$o.lastLogonTimeStamp = [datetime]::FromFileTime($result.Properties.Item('lastlogontimestamp')[0])
}
$o.name = $result.Properties.Item('name')[0]
if ($result.Properties.Item('operatingsystem')) {
$o.operatingSystem = $result.Properties.Item('operatingsystem')[0]
}
# TODO: change this if your environment differs
$si = $result.path.IndexOf('OU=')
if ($si -eq -1) {
$si = $result.path.IndexOf('CN=Computers,')
}
$o.ou = $result.path.Substring($si)
if ($null -ne $result.Properties.Item('pwdlastset')) {
$o.pwdLastSet = [datetime]::FromFileTime($result.Properties.Item('pwdlastset')[0])
}
$o.sAMAccountName = $result.Properties.Item('samaccountname')[0]
$o.whenCreated = $result.Properties.Item('whencreated')[0]
# add the data to the in-memory database
$nr = $script:ds.Tables[$tbl].NewRow()
$nr['distinguishedName'] = $o.distinguishedName
$nr['lastLogonTimeStamp'] = $o.lastLogonTimeStamp
$nr['name'] = $o.name
$nr['operatingSystem'] = $o.operatingSystem
$nr['ou'] = $o.ou
$nr['pwdLastSet'] = $o.pwdLastSet
$nr['sAMAccountName'] = $o.sAMAccountName
$nr['whenCreated'] = $o.whenCreated
[void]$script:ds.Tables[$tbl].Rows.Add($nr)
}
if ($IncludeBitlocker) {
GetBitLockerInfo
}
# Return all the rows
$script:ds.Tables[$tbl].Select()
}
}
catch {
throw
}
finally {
if ($script:ds) {
$script:ds.Dispose()
}
# release our resources
if ($RootDE) {
$RootDE.Close()
$RootDE.Dispose()
}
if ($script:searcher) {
$script:searcher.Dispose()
}
}