Public/Get-ADComputerOrganizationalUnit.ps1

<#
.SYNOPSIS
    Retrieves the Organizational Unit (OU) for a specified computer account in Active Directory using dynamic Global Catalog discovery.
 
.DESCRIPTION
    The Get-ADComputerOrganizationalUnit function queries Active Directory to find the OU of a given computer name using a dynamically determined Global Catalog.
    It outputs the distinguished name (DN) and the name of the OU where the computer is located.
 
.PARAMETER ComputerName
    The name of the computer for which the OU is being queried. This parameter is mandatory and accepts input from the pipeline.
 
.EXAMPLE
    PS> Get-ADComputerOrganizationalUnit -ComputerName "DESKTOP-12345"
    This example retrieves the OU details for the computer named "DESKTOP-12345".
 
.OUTPUTS
    PSCustomObject
    Outputs the distinguished name (DN) and the name of the OU.
 
.NOTES
    Requires Active Directory module for PowerShell and appropriate permissions to query AD objects.
#>


function Get-ADComputerOrganizationalUnit
{
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$ComputerName
    )

    Process
    {
        try
        {
            # Discover the Global Catalog dynamically
            $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
            $globalCatalog = ($forest.RootDomain).Name
            $ldapPath = ($globalCatalog -split "\.") | ForEach-Object { "dc=$_" }
            $ldapPath = $ldapPath -join ","
            $gcPath = "GC://$ldapPath"

            Write-Verbose "Using Global Catalog: $gcPath"

            $strFilter = "(&(objectCategory=Computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(Name=$ComputerName))"
            $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
            $objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry($gcPath)
            $objSearcher.PageSize = 1000
            $objSearcher.Filter = $strFilter

            $result = $objSearcher.FindOne()
            if ($null -ne $result)
            {
                 $DN = $result.Properties.distinguishedname
                 $ADVal = [ADSI]"LDAP://$DN"
                 $WorkOU = $ADVal.Parent
                 [pscustomobject]@{
                    DN  = $WorkOU -replace 'LDAP://',''
                    OUName  = (($WorkOU -replace 'LDAP://','').split(",")[0]).split("=")[1]
                 }
            }
            else
            {
                Write-Output "No results found for computer: $ComputerName"
            }
        }
        catch
        {
            Write-Error "Failed to retrieve OU for computer $ComputerName : $_"
        }
        finally
        {
            $objSearcher.Dispose()
        }
    }
}