Link to home
Start Free TrialLog in
Avatar of IT _Admin0723
IT _Admin0723Flag for United States of America

asked on

Pre-Check Before Deleting OUs

Hello experts,

Can someone please share a handy PS to pre-check a list of multiple OUs (100s) to ensure there are no objects (users and/or computers) residing in it? I wanted to run this before I go ahead and delete them.

Thank you for all your assistance!
Avatar of J0rtIT
J0rtIT
Flag of Venezuela, Bolivarian Republic of image

Well I made it up

import-module activedirectory


function Reverse-HashTable{
    [CmdletBinding()]
    param(
        [Parameter(mandatory=$true,position=0)]$Table
    )
    begin{
        if($table.count -le 0){
            Write-Host -ForegroundColor Red "There's nothing to get inverted the input value is empty or null"
            break;
        }
    }
    process{
        $outTable=@()

        for($i = $Table.count -1; $i -ge 0;$i--){
            $outTable+=$Table[$i]
        }
    }
    end{
        return $outTable
    }

}
function remove-OUs{
    [CmdletBinding()]
    param(
        [Parameter(mandatory=$true,position=0)]$OUs
    )
    process{
        
        if($OUs.Count -le 0){
            write-host -ForegroundColor Red  "There is nothing to remove in the Input $OUs"
        }
        else{
            $reverse= Reverse-HashTable -Table $OUs

            foreach($ou in $reverse){
                Write-Host -ForegroundColor DarkCyan "Removing the Organizational unit: $($ou.OUname)"
                Get-ADOrganizationalUnit -Identity $ou.DistinguishedName  | Set-ADObject -ProtectedFromAccidentalDeletion:$false -PassThru |  Remove-ADOrganizationalUnit -Confirm:$false
            }
        }
    }
}

[Array]$OUs=@()
Get-ADOrganizationalUnit -Filter * | %{ 
		$OUInfo =Get-ADObject -SearchBase $_.DistinguishedName -Filter {Objectclass -ne "OrganizationalUnit"}
        if($OUInfo){$OUs+= new-object psobject -property @{"OUName" =$_.Name;"DistinguishedName" =$_.DistinguishedName; "ObjectsFound"=$OUInfo} }
        else{   $OUs+= new-object psobject -property @{"OUName" =$_.Name;"DistinguishedName" =$_.DistinguishedName; "ObjectsFound"=$null} }
	}


write-host "The OUs found empty in your environment are":
$filtered =$OUs | where{ $_.ObjectsFound -eq $null}
$filtered
$answer= Read-Host "This are the OUs that are empty, are you sure you want to remove them? (Y/N)"

switch($Answer){
	"Y"{
		remove-OUs -OUs $filtered
	}	

}

Open in new window


User generated image
Avatar of IT _Admin0723

ASKER

@ Jose thanks so much for your fast reply and assistance! Much appreciated. I actually have a list (txt in DN format) that I'd like to use to check in specific vs doing a domain wide querying....
ASKER CERTIFIED SOLUTION
Avatar of J0rtIT
J0rtIT
Flag of Venezuela, Bolivarian Republic of image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Answered