Searching organizational units

The following code sample finds organizational units with no owners and outputs their names.

ADSI
[Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi")

$domainDN = "DC=domain,DC=com"

# Connect to the Adaxes service
$ns = New-Object "Softerra.Adaxes.Adsi.AdmNamespace"
$service = $ns.GetServiceDirectly("localhost")

$searcher = $service.OpenObject("Adaxes://$domainDN", $null, $null, 0)

$searcher.Criteria = New-AdmCriteria "organizationalUnit" {directOwners -empty $true}
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
try
{
    # Execute search
    $searchResultIterator = $searcher.ExecuteSearch()

    foreach ($searchResult in $searchResultIterator.FetchAll())
    {
        $ouPath = $searchResult.AdsPath
        $ou = $service.OpenObject($ouPath, $null, $null, 0)
        Write-Host $ou.Name
    }
}
finally
{
    # Release resources
    $searchResultIterator.Dispose()
}
PowerShell
Import-Module Adaxes

$domainDN = "DC=domain,DC=com"

$organizationalUnits = Get-AdmOrganizationalUnit `
    -Filter {adm-ManagedByList -notlike "*" -and managedBy -notlike "*"} `
    -SearchBase $domainDN -Server "domain.com" `
    -SearchScope Subtree -AdaxesService localhost

foreach ($ou in $organizationalUnits)
{
    Write-Host $ou.Name
}

See also