≡ Menu

Pstip# Quick way to check if a OU exists in Active Directory

While working on some PS stuff today related to active directory, I came across a need to verify if the given OU(Organization Unit) exists or not. Basically, I am taking OU as input to one of my scripts and would like to validate if that OU exists before doing any processing.  After a little bit of research, I found below is quick and useful.

function Test-ADOU {            
[cmdletbinding()]            
param(            
[string] $OuPath            
)            
try {            
    if([ADSI]::Exists("LDAP://$OuPath")) {            
        Write-Host "Given OU exists"            
    } else {            
        Write-Host "OU Not found"            
    }            
} catch {            
    Write-Host "Error Occurred while querying for the OU"            
}            
}

In the above code, the core part that checks for OU existence is [ADSI]::Exists() static method. It returns true if  OU exists, otherwise returns false. It will generate appropriate errors if it can not reach the domain you are querying.

Let us see a quick demo to see how it works. My AD structure is like below.

In the below screen first I queried for OldComps OU in the above structure and the the function returned saying “Given OU Exists”. I changed the input OU name to something that doesn’t exists and it returned the not found error message. In the third attempt, I changed the domain name to a non-existing domain.

Hope this helps…

 

Comments on this entry are closed.

  • Alex Wells July 22, 2014, 8:42 pm

    Function Check-OUExists{

    [CmdletBinding()]
    Param(#Param Open
    [parameter(Mandatory=$true,Helpmessage=”Enter the name of the OU you wish to check”)]
    [String]$OUToSeek

    )

    begin
    {
    #Puts All OU names into an Array
    $AllOUsNames = (Get-ADOrganizationalUnit -Filter *).name
    }

    Process
    {
    #Checks if the Array contains the OU being seeked
    $Result = $AllOUsNames -contains $OUToSeek
    #returns the result
    return ,$result
    }
    End
    {
    }
    }

    • Sitaram Pamarthi July 22, 2014, 9:03 pm

      I think you should call it as Search-ADOU :-). Thanks for posting

  • Chakram Blogger November 7, 2014, 2:15 pm
    • Sitaram Pamarthi November 8, 2014, 10:38 am

      Hi, Thanks for commenting. Definitely a good script. But cannot compare with the one given here. Both are intended for different purpose and scope is different.