Powershell: Delete inactive computers from Active Directory.

In your Active Directory structure, computers that are registered but not used for a long time can cause confusion and poor performance in time; therefore, it is important to identify and erase them. Inactive computers should not only be deleted from active directory, but also from dns. The fact that a computer that is no longer in our network is in our dns records can cause confusion.

In the following script, we identify computers with non-server operating system that are not active for specified number of days, and we delete these computers, recording their FQDN in a log file. We are using ‘LastLogonDate’ attribute to identify computers’ last logon date.


$fn = (Get-Date).tostring("ddMMyyyy") + ".csv"
$file ="c:\scripts\reports\RemovedInactiveComputers-" + $fn
$log = "c:\scripts\logs\deletedComputers.txt"

$remove = $true # whether to delete inactive computers
$days = 90 # number of days
$numberOfDays = (Get-Date).AddDays(-$days) # identify date: currentdate - $days

$DNSServer = "dc1" # dns server FQDN
$DNSZone = "test.local" # dns zone
$logDNS = "c:\scripts\logs\removedFromDNS.txt" # log file name

Import-Module ActiveDirectory

Get-ADComputer -Property Name, lastLogonDate, OperatingSystem -Filter {lastLogonDate -lt $numberOfDays -and OperatingSystem -notlike "*Server*"} |
Sort lastLogonDate | Export-Csv $file # identify and export the list of computers with non-server OS, inactive by $numberOfDays.

$computers = Import-Csv $file
$removedPcs =@() # initialize variable

if($remove -and $computers.length -gt 0) {
foreach($comp in $computers){
$pc = Get-ADComputer $comp.Name -Properties DistinguishedName | Select-Object DistinguishedName
$recordName = $comp.Name
$recordType = "A"
Remove-ADObject -Identity $comp.DistinguishedName -Recursive -Confirm:$false # delete from Active Directory.
$removedPcs += $pc | # add the deleted computer's FQDN to array variable
# Delete from DNS
$cmdDelete = "dnscmd $DNSServer /RecordDelete $DNSZone $recordName $recordType /f"
$aRecord = [System.Net.DNS]::GetHostByName($recordName).HostName | # check if dns record for the computer exist.
Write-Host "info :$recordName found dns record, deleting..."
Invoke-Expression $cmdDelete
write-host "info:$recordName dns record deleted!"
$recordName | Out-File $logDNS -Append # saving computers' FQDN deleted from DNS into a log file..
}catch{ "hata: $recordName can't delete dns record!" }
}catch{"hata: $recordName dns record not found!"}

} #foreach loop
$removedPcs | Out-File $log -Append # saving computers' FQDN deleted from Active Directory into a log file.
} # if statement
else{ Write-Host "inactive computers not found!"}


Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir