Wednesday, January 4, 2012

PowerShell: Protect All AD Objects in Specific OUs

A strong need came up to set all AD objects in specific OUs with "Protect Object from Accidental Deletion"; however, some of these OUs were in different domains and this would require that would require a specific server setting for the Get-ADObject command. I solved this issue by using a hashtable to store the OU and DC info.

Enjoy.

##############################################################################

# Script Name: AD_Prevent_Accidental_Deletion.ps1

# Version: 1.5

# Author: Dean Bunn

# Last Edited: 01/01/2011

# Description: Protect All AD Objects in Select OUs from Accidental Deletion

##############################################################################

#Add Active Directory Module

Import-Module ActiveDirectory

#Create a HashTable to Hold OUs

$hOU = @{}

#Add OU and DC Info into HashTable

$hOU["ou=Payroll,dc=campus,dc=edu"] = "dccmp1.campus.edu"

$hOU["ou=Payroll,dc=campus,dc=edu"] = "dccmp1.campus.edu"

$hOU["ou=Marketing,dc=phys,dc=campus,dc=edu"] = "dcphys1.phys.campus.edu"

$hOU["ou=Marketing,dc=phys,dc=campus,dc=edu"] = "dcphys1.phys.campus.edu"

#Loop Through the OU HashTable

foreach($key in $hOU.keys)

{

#Assign OU and Server Names to Local Variables (Easier to Read Command)

$srchBase = $key.ToString()

$srvr = $hOU[$key].ToString()

#Set "Protect Object from Accidental Deletion" on All OU AD Objects

Get-ADObject -Filter * -SearchBase $srchBase -ResultPageSize 500 `

-SearchScope Subtree -Properties ProtectedFromAccidentalDeletion -Server $srvr `

| Where {$_.ProtectedFromAccidentalDeletion -eq $false} `

| Set-ADObject -ProtectedFromAccidentalDeletion $true -Server $srvr

}


No comments: