Delete Multiple Active Directory Organizational Units Using PowerShell and CSV

In this blog post, I will show you how I delete multiple Active Directory OUs with the Protected From Accidental Deletion feature on from a CSV file.

Deleting many OUs with Sub OUs can be a pain when you need to do a deep AD clean up or programmatically manage AD.

This method can help you automate this process and save time.

CSV File

The format of the CSV file needs to look as follow:

OUpath
"OU=Name, DC=Domain, DC=local"

Add as many OU paths that you need and save the file.

PowerShell Script

In the example, below, I have a PowerShell script that will load the CSV file and do the following:

  • Remove the ProtectedFromAccidentalDeletion value from the OU before deleting it (if it is enabled)
  • Delete OUs and Sub OUs
  • Output the deleted OUs to the screen
$x = Import-Csv .\core.csv
foreach($entry in $x)
{
$entry.OUPath

Get-ADOrganizationalUnit -Identity $entry.OUPath | Set-ADObject -ProtectedFromAccidentalDeletion:$false | `
Remove-ADOrganizationalUnit -Verbose -Recursive -Confirm:$false

}

Save the script and run it, just make sure you put the correct OUs.

Processing…
Success! You're on the list.

Posted

in

,

by