powershellactive-directory

Syntax for Defining AD sub-OUs in Powershell


I am trying to create a script that:

So far I have created two variables called $SourceOU and $TargetOU.

$SourceOU contains the OU where PCs are placed by default.
$TargetOU contains the OU where I would like to move the PC to, if the pc is located in $SourceOU.

I'm wondering how I would format the syntax for an OU with several sub-OUs For example, a default OU contain a PC would have this path ntds://testdomain.com/Deployments/Texas/Austin

Would I format the variable definition like this:

$SourceOU = "OU=Deployments, OU=Texas, OU=Austin, DC=testdomain, DC=com" 

Thank you.

# default location for imaged PCS 
# ntds://testdomain.com/Deployments/Texas/Austin

$SourceOU = "OU=Deployments, OU=Texas, OU=Austin, DC=testdomain, DC=com"

Solution

  • A Distinguished Name (or DN) (eg. OU=Department,DC=domain,DC=tld) is read "backwards" compared the canonical object path (eg. domain.tld/Department) - the first component describes the object itself, the following component its parent, and so on.

    So in your example the correct DN is likely:

    OU=Austin,OU=Texas,OU=Deployments,DC=testdomain,DC=com
    

    Note that the RDN label (OU or DC in the example above) is dependent on the type of object or container being described - for any organizational unit the RDN label is OU, whereas for most directory objects (users, computers, contacts, etc.) and built-in containers (including the default Users and Computers containers), the RDN attribute is the object's common name and the label is thus CN.

    If you're ever in doubt, simply search for a given object - most query tools, including the RSAT ActiveDirectory Module, will always return the DN for a given object by default:

    # find the DN for the account object of the current computer
    $computer = Get-ADComputer -Identity $env:COMPUTERNAME 
    
    Write-Host "Found computer account object at $($computer.distinguishedName)"