Search code examples
powershellactive-directorysid

Querying Active Directory user information using Powershell - seemingly equivalent syntax, different results?


I have a simple Powershell function to perform an Active Directory LDAP lookup based on the SID of a user:

function SidToAdUser($sid) {[adsi]("LDAP://<SID=" + $sid + ">")}

If I wish to read an attribute from the returned User object, accessing it via an intermediary variable works fine:

$ad = SidToAdUser("S-1-5-21-968173855-142910291-87512543-670313")
$ad.department

However, attempting to access it directly from the return value of the function, like this:

SidToAdUser("S-1-5-21-968173855-142910291-87512543-670313").department

elicits an error:

format-default : The following exception occurred while retrieving member "distinguishedName": "An invalid dn syntax has been specified.
"
    + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand

Can anyone advise why exactly this would be the case, and how to correct it?

Thank you.


Solution

  • Your function call syntax is wrong.

    (SidToAdUser S-1-5-21-968173855-142910291-87512543-670313).department
    

    In powershell, function arguments are specified as space-separated values after the function name, not enclosed in parens.