Disable & Move old AD Computer Objects

A quick script to take a list from CSV and disable, then move objects in AD…

Remember everyone – don’t just cut & paste scripts from the internet and run them, without understanding what they are doing first, ff in doubt – DON’T run it!

Always build in sanity checking and also test on a sample set of data/test environment.

#Check AD record.
$computerlist=Import-Csv c:\temp\computers.csv
$computerlist | ForEach-Object {
$adobj = $_

try
{
$adcomp= Get-ADComputer -Identity $adobj.computername 
$errorvar = '0' 
}
catch
{
Write-host "Unable to find a computer" ($adobj.computername)
$errorvar = '1'
}

if ($errorvar -ne '1')
 {
 try
 {
 Set-ADComputer -Identity $adcomp -Enabled $false -ErrorAction Stop
 $errorvar= '0'
 }
 catch
 {
 Write-Host "Unable to disable AD account for" ($adobj.computername)
 $errorvar='1'
}
}
else
{
}
if ($errorvar -ne '1')
{
 try
 {
 Move-ADObject -Identity $adcomp -TargetPath 'OU=TBDelete,DC=mydomain,DC=local'
 $errorvar= '0'
 }
 catch
 {
 Write-Host "Unable to move AD account for" ($adobj.computername)
 $errorvar='1'
}
 }
 else
 {
 }
Clear-Variable -Name adcomp
}
Advertisements

Author: Hyper-Vine

Microsoft Certified Solutions Expert - Cloud Platform & Infrastructure System Center Admin - 2007, 2012 & 2016 Infrastructure Consultant

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s