Deleting an AD object via a top level search

All, 

I am creating a script that we will use for Decommissioning PC's and what I've thrown together does work. See below:

#Import SCCM Module
import-module '\\networkdrive\ConfigurationManager.psd1'

#Import Active Directory Module
Import-Module '\\networkdrive\ActiveDirectory.psd1'
cd CAS:

#Enter Machine Name
$Name = Read-Host 'What is the machine name?'

#Remove from SCCM
Get-CMDevice -Name "$Name"
Remove-CMDevice -DeviceName "$Name" -Force

$ErrorActionPreference= 'silentlycontinue'

#UKLON
#Disable UK Machine AD Account
Disable-ADAccount -Identity "CN=$Name,OU=Windows 7 Prod Workstations,OU=Desktops,OU=Computers,OU=UK,DC=XXX,DC=XXXXXX,DC=net"

#Move UK Machine Object
Move-ADObject -Identity "CN=$Name,OU=Windows 7 Prod Workstations,OU=Desktops,OU=Computers,OU=UK,DC=XXX,DC=XXXXXX,DC=net" -TargetPath "OU=Disabled Computer Accounts,OU=Computers,OU=UK,DC=XXX,DC=XXXXXX,DC=net"

----

So you can see what it does, deletes it from SCCM then disables it in AD and moves it to the disabled machine OU. 

Currently I've a line for each Prod Workstation OU, but obviously we've got our testing ones, other bits and pieces etc. So save me having to enter a line for each specific OU is there a way I can just tell it to search from the root of the domain? 

TIA

Jake

February 17th, 2015 11:40am

Hi Jake,

Here's something you can play with:

$computerName = Read-Host 'Enter the computer name to disable'

try {

    $computer = Get-ADComputer -Identity $computerName -ErrorAction Stop

    Disable-ADAccount -Identity $computer.DistinguishedName -WhatIf
    Move-ADObject -Identity $computer.DistinguishedName -TargetPath 'OU=Disabled Computers,DC=domain,DC=com' -WhatIf

} catch {

    Write-Warning "Error finding $computerName in AD"

}

Free Windows Admin Tool Kit Click here and download it now
February 17th, 2015 11:56am

Thanks very much, I'll give this a go! 

Jake

February 18th, 2015 3:31am

Cheers, you're very welcome. Let us know if you run into problems.
Free Windows Admin Tool Kit Click here and download it now
February 18th, 2015 6:42pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics