Hi there,
If you are looking to tidy up your Active Directory by finding inactive computer, I have a PowerShell script that can do just that. Save and run this script on your domain controller. This is just a audit tool and wont delete any thing.
- Save the code with a ".PS1" extension.
- Open PowerShell as an admin and run the script.
Clear-Host
Write-Host -ForegroundColor yellow " FIND INACTIVE USERS/STALE COMPUTERS"
# Prompt user for number of days of inactivity
$daysInactive = Read-Host "Enter number of days of inactivity"
# Calculate the threshold date
$thresholdDate = (Get-Date).AddDays(-$daysInactive)
# Function to recursively fetch OU path
function Get-OUPath {
param (
[string]$DN
)
# Split DistinguishedName into its components
$components = $DN -split ','
$ouPath = @()
# Iterate through components to construct OU path
for ($i = 1; $i -lt $components.Count; $i++) {
if ($components[$i] -match '^OU=(.+)$') {
$ouPath += $Matches[1]
}
}
# Reverse the OU path to get correct order (child to parent)
$ouPath = $ouPath -join '\'
return $ouPath
}
# Search for inactive computers in Active Directory
$inactiveComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $thresholdDate -and Enabled -eq $true} -Properties LastLogonDate, DistinguishedName |
Select-Object Name, LastLogonDate, @{
Name="OUPath";
Expression={
# Call Get-OUPath function to retrieve OU path
Get-OUPath -DN $_.DistinguishedName
}
}
# Display results in Out-GridView
$inactiveComputers | Out-GridView