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!
IT_Admin XXXXAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
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


Screenshot_2.png
0
IT_Admin XXXXAuthor Commented:
@ 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....
0
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
Ohh that's easier :)
Untested Code.

import-module activedirectory
$inputFile="D:\input.txt"

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 $OUs){
                Write-Host -ForegroundColor DarkCyan "Removing the Organizational unit: $($ou.DN)"
                Get-ADOrganizationalUnit -Identity $DN  | Set-ADObject -ProtectedFromAccidentalDeletion:$false -PassThru |  Remove-ADOrganizationalUnit -Confirm:$false
            }
        }
    }
}

#The order should be from "DEEPER to root" so : domain.com/OU1/OU2/OU3 MUST BE before that domain.com/OU1/OU2 in the text file to work properly
$OUs=@()


Get-Content $inputFile | %{ 
		$OUInfo =Get-ADObject -SearchBase $_ -Filter {Objectclass -ne "OrganizationalUnit"}
        if($OUInfo){$OUs+= new-object psobject -property @{"DN"=$_; "ObjectsFound"=$OUInfo} }
        else{       $OUs+= new-object psobject -property @{"DN" =$_;"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"{
        #if the order of the file is OU2 then OU2/OU3 maybe you can check if having the table reversed fix the problem
        #$filtered = reverse-hashtable $filtered
		remove-OUs -OUs $filtered
	}	

}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
Answered
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.