Delete multiple AD OUs that have protection on them

703 Views Asked by At

I am trying to delete multiple ou's, not in the same parent\child structure but multiple OU's next to each other. Example:

OU=legal,OU=department,DC=company,DC=com
OU=marketing,OU=department,DC=company,DC=com
OU=advertising,OU=department,DC=company,DC=com

I can delete a single OU out with protection using the following:

Get-ADOrganizationalUnit -Identity 'OU=legal,OU=department,DC=company,DC=com' |
Set-ADObject -ProtectedFromAccidentalDeletion:$false -PassThru |
Remove-ADOrganizationalUnit -Confirm:$false

But I'm unsure of how to get it to work with a foreach and a text file. Any help would be greatly appreciated

1

There are 1 best solutions below

0
On

First I created the text file "C:\Temp\OU's.txt". With all the OU's inside it.

    $ous = Get-Content -Path "C:\Temp\OU's.txt"

foreach($ou in $ous){
    try{
        Get-ADOrganizationalUnit -Identity $ou |
        Set-ADObject -ProtectedFromAccidentalDeletion:$false -PassThru |
        Remove-ADOrganizationalUnit -Confirm:$false -WhatIf
        Write-Host "Succesfully deleted $ou" -ForegroundColor Green
    }catch{
        Write-Host "Failed to delete $ou because '$($_.Exception.Message)'" -ForegroundColor Red
    }
}

Note the -WhatIf in the end like Bill_Stewart said, to make sure you only see what is about to happen! Remove it and all the OU's stated in the text file will be removed.