1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | # =========================================================================== # This script pulls a list of all domain joined servers and prints the # last connected time. The server is in red if this time is older than the # number of days. Beware that just because the server hasnt connected in # the specified number of days, doesnt necessarily mean that the server # can be deleted. Instead, move the server into the Deactivated OU and # only when you are sure, delete the server. # # May need to run this script as an OS user that is domain joined. # =========================================================================== $daysInactive = 30 $cutoffDate = (Get-Date).AddDays(-$daysInactive) # Get all computer accounts $computers = Get-ADComputer -Filter * -Properties Name, OperatingSystem, LastLogonTimeStamp, DistinguishedName # Sort by name $computers = $computers | Sort-Object Name # Helper to extract OU path from DistinguishedName function Get-OUFromDN($dn) { ($dn -split ',') -notmatch '^CN=' -join ',' } # Display header Write-Host ("{0,-30} {1,-30} {2,-22} {3}" -f "Name", "Operating System", "Last Logon", "Organizational Unit") -ForegroundColor Cyan # Print each computer foreach ($comp in $computers) { $lastLogon = [DateTime]::FromFileTime($comp.LastLogonTimeStamp) $isInactive = $lastLogon -lt $cutoffDate $os = if ($comp.OperatingSystem) { $comp.OperatingSystem } else { "Unknown / Possibly Linux" } $ou = Get-OUFromDN $comp.DistinguishedName $output = "{0,-30} {1,-30} {2,-22} {3}" -f $comp.Name, $os, $lastLogon, $ou if ($isInactive) { Write-Host $output -ForegroundColor Red } else { Write-Host $output -ForegroundColor Green } } |