1BilliumDollars
1BilliumDollars

Reputation: 149

Convert Distinguished Name to SamAccountName without Get-ADUser

My machines have the original build of PowerShell v2.0, so Get-ADUser will not work. I am trying to convert the manager property from it's distinguishedname to it's SamAccountName.

$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$searcher.FindOne().Properties.manager

This works perfectly if I had Get-ADUser:

(get-aduser (get-aduser $user -Properties manager).manager).samaccountName

Grabbed get-aduser statement from here..

Upvotes: 2

Views: 6095

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

You can use the distinguished name to retrieve the user object that will give you the sAMAccountName:

$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$manager  = [adsi]('LDAP://' + $searcher.FindOne().Properties.manager)
$manager.sAMAccountName

If the distinguished name contains special characters that would require escaping you could also use an additional ADSISearcher instead:

$searcher  = [adsisearcher]"(samaccountname=$env:USERNAME)"
$manager   = $searcher.FindOne().Properties.manager
$searcher2 = [adsisearcher]"(distinguishedName=$manager)"
$searcher2.FindOne().Properties.sAMAccountName

Upvotes: 2

Bill_Stewart
Bill_Stewart

Reputation: 24525

$ADS_ESCAPEDMODE_ON = 2
$ADS_SETTYPE_DN = 4
$ADS_FORMAT_X500_DN = 7
$Pathname = new-object -comobject "Pathname"
[Void] $Pathname.GetType().InvokeMember("EscapedMode", "SetProperty", $null, $Pathname, $ADS_ESCAPEDMODE_ON)

$searcher = [ADSISearcher] "(sAMAccountname=$Env:USERNAME)"
$managerDN = $searcher.FindOne().Properties["manager"]
if ( $managerDN ) {
  [Void] $Pathname.GetType().InvokeMember("Set", "InvokeMethod", $null, $Pathname, @($managerDN[0], $ADS_SETTYPE_DN))
  $escapedDN = $Pathname.GetType().InvokeMember("Retrieve", "InvokeMethod", $null, $Pathname, $ADS_FORMAT_X500_DN)
  ([ADSI] "LDAP://$escapedDN").Properties["sAMAccountName"][0]
}

Get the manager property for the current user (a distinguished name), escape it using the Pathname object, bind to it using the [ADSI] type accelerator, and retrieve the manager's sAMAccountName attribute.

Upvotes: 0

Related Questions