Tag Archives: Active Directory

Find unactive AD computer objects that are still enabled

Wants to know which computer in your AD is no longer used, but are still enabled in the AD. Schedule this script to run on a monthly basis and get an email with all computers not used in the last 365 days.

Import-Module ActiveDirectory

$date = get-date

$systems = Get-ADComputer –filter * -prop Lastlogondate,passwordLastSet,whencreated,enabled,OperatingSystem,description |
Where { $_.passwordLastSet –eq $null –or $_.passwordLastSet –lt (Get-Date).AddDays(-365) -and $_.lastlogondate –lt (Get-Date).AddDays(-365) -and $_.enabled -eq “TRUE” }|
select Name,
LastLogonDate,
PasswordLastSet,
whencreated,
OperatingSystem,
description,
DistinguishedName |
export-Csv C:\temp\InactiveComputers.csv -notypeinformation -Delimiter “;”

function sendMail{

Write-Host “Sending Email”

#SMTP server name
$smtpServer = “mail.local”

#Creating a Mail object
$msg = new-object Net.Mail.MailMessage

#Attach output file
$file = “C:\temp\InactiveComputers.csv”
$att = new-object Net.Mail.Attachment($file)

#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#Email structure
$msg.From = “srv-0001@mail.local”
$msg.ReplyTo = “user@mail.local”
$msg.To.Add(“recepient@mail.local”)
$msg.subject = ” Inactive computer accounts to be removed”
$msg.body = “This is the email Body.”
$msg.Attachments.Add($att)

#Sending email
$smtp.Send($msg)

}
#Send mail
sendMail

Powershell to disable unused computer AD accounts.

Here is a powershell script that can be used to cleanup old computer AD accounts:


Import-Module ActiveDirectory

$date = get-date

$systems = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 365

foreach($computer in $systems){

$computer | select-object Name, OperatingSystem, DistinguishedName, LastLogonTimeStamp >> “C:\Scheduled Tasks\AD Cleanup\SystemInfo.csv”

$computer | disable-adaccount

$computer | move-adobject -targetpath “ou=Dormant Computers,dc=xxxx,dc=xxx”

write-host “$computer will be moved to Dormant computers”

}

First we load the Active Directory Module into Powershell. This has to be added as a Winodws Feature first.
Then we search the AD for all computer accounts which have been inactive for the last 365 days.
In the foreach loop we write the name of the server and LastLogonDate to a csv file to keep as a log.
Then we disable the account and move it to a OU where we keept disabled accounts.
Last we output a stsus message to the console.

Staffan Olofsson