How can I get the current OU with a PowerShell login script?

I am setting up a Terminal Server 2008 which will be used by different client organisations, each with multiple individual user accounts. I would like each client organisation to have a drive mapped to \server\clients\

Their OU name is also their client name, so I would like to be able to find their current OU and then use it for the mapping command. The OUs are hierarchicals, so it is the bottom-most OU name I need.

Example
OU:
Dedicated Clients\AjaxCorp

Should get a drive mapped to
\\server1\shares\AjaxCorp

Any suggestions on how I can get the OU? I am sure it must be easy, I just haven't figured it out...

I did find information about how to do this with VB script, but as it is a whole new environment I thought it would be nice to use PowerShell instead.


Solution 1:

This will get you the LDAP path to the current computer:

$objDomain = New-Object System.DirectoryServices.DirectoryEntry  
$strFilter = "(&(objectCategory=computer)(name=" + $env:computername + "))"

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher  
$objSearcher.SearchRoot = $objDomain  
$objSearcher.Filter = $strFilter

$strPath = $objSearcher.FindOne().Path

From the result in $strPath, you should be able to build a network path to the share you need.

Solution 2:

To actually return an object of type Microsoft.ActiveDirectory.Management.ADOrganizationalUnit of a User Object, use this:

Get-ADOrganizationalUnit -Identity $(($adUser = Get-ADUser -Identity $env:USERNAME).DistinguishedName.SubString($adUser.DistinguishedName.IndexOf("OU=")))

The same can be accomplished for a computer:

Get-ADOrganizationalUnit -Identity $(($adComputer = Get-ADComputer -Identity $env:COMPUTERNAME).DistinguishedName.SubString($adComputer.DistinguishedName.IndexOf("OU=")))