Disable and removal of Computer accounts
Hi,
I made a script to disable old computer accounts.
My Sysadmin asked me to disable after 180 days and remove them after a year.
My goal is to disable computer accounts after 180 days and export to CSV
then delete computer accounts after 356 days and export to CSV.
Import-Module ActiveDirectory
# Set the Parameters since last logon
$DaysInactive = 180
$InactiveDate = (Get-Date).Adddays(-($DaysInactive))
$ForDisableLog = "C:\scripts\ComputerAccounts\Logs\For_Disable$((Get-Date).ToString('dd-MM-yyyy')).csv"
#-------------------------------
# FIND INACTIVE COMPUTERS
#-------------------------------
# Automated way (includes never logged on computers)
$Computers_For_Disable = Search-ADAccount -AccountInactive -DateTime $InactiveDate -ComputersOnly -SearchBase "DC=staff ,DC=local" | Where-Object {$_.distinguishedname -notlike "*,OU=Servers,*"} | Where-Object {$_.distinguishedname -notlike "*,OU=Test,*"} | Where-Object {$_.distinguishedname -notlike "*,OU=IT,*"} | Where-Object {$_.distinguishedname -notlike "*,OU=Laptops,*"} | Where-Object {$_.distinguishedname -notlike "*,CN=Computers,*"} | Select-Object Name, LastLogonDate, Enabled, DistinguishedName
#-------------------------------
# REPORTING
#-------------------------------
# Export results to CSV
$Computers_For_Disable | Export-Csv "C:\scripts\ComputerAccounts\Logs\For_Disable$((Get-Date).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Encoding UTF8