Powershell – How to get the current OU with a PowerShell login script

powershellwindows-server-2008

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.

Best Answer

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.