简体   繁体   中英

Delete multiple AD OUs that have protection on them

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM