Protect OU’s from accidental deletion

Here is a quick and easy one line PowerShell script to set all of the Organizational Units (OU's) in your Active Directory (AD) to protect from accidental deletion. I know others have posted similar information, but it never hurts to raise awareness of this setting. And also, since I run into many customers that do not fully leverage the power of PowerShell to quickly set this value instead of having an administrator click in the GUI to verify or not each and every OU in the environment has this value set.

Back in 2000 AD, this value didn't exist. With a single click, administrators could delete an entire OU. That behavior was not ideal. By 2003 AD, the Product Group (PG) introduced a check box that states, ‘Protect object from accidental deletion’. By default, the PG decided not to change all OU's to this value, but to just add the attribute.

Once you’ve set this attribute and you delete an OU, what appears is a prompt asking you, are you sure you want to delete this object. Now it's easy enough to just click by this and accept it, but at least there is a pop up.

Here is a one liner to list OU's with protect from accidental deletion not enabled:

Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {$_.ProtectedFromAccidentalDeletion -eq $false}

You have to launch AD PowerShell module to get this cmdlet to work. The syntax is: get the Active directory OU and filter for the property that equals 'Protect from Accidental Deletion'. Take that grouping of objects, pipe it to only objects where the value is false, and a list will be presented.

Now that you have a list of the objects this effects, you can list them in your change management process for review and communication to other teams.

This next script then takes those values, and pipes them to a 'set' cmdlet that changes the accidental deletion value to true.

Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | where {$_.ProtectedFromAccidentalDeletion -eq $false} | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true

There you go, an extremely easy way to help protect your AD OU's from being accidentally deleted. Fortunately for administrators, as of 2008R2 Forest Functional Level, there is the built in AD Recycle Bin that allows for an un-delete action of deleted AD objects.

Mike