Search code examples
windowspowershellactive-directoryadsi

Get the domain name of the user of ADSI object?


In the following script, it will print all the users of the groups. However, the domain name is missing (Some users are in different Windows domain)?

$computer = [ADSI]"WinNT://$server,computer"

$computer.psbase.children | ? { 
    $_.psbase.schemaClassName -eq 'group'
} | % {
    $gn = $_.name.ToString()
    write-host $gn

    write-host "------"
    $group =[ADSI]$_.psbase.Path
    $group.psbase.Invoke("Members") | % {
        $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
    } 
}

Solution

  • Try fetching the SID instead of the name and translate that back to a username:

    $computer.psbase.children | ? {
        $_.psbase.schemaClassName -eq 'group'
    } | % {
        $gn = $_.name.ToString()
        write-host $gn
    
        write-host "------"
        $group =[ADSI]$_.psbase.Path
        $group.psbase.Invoke("Members") | % {
            $bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)
            $sid = New-Object Security.Principal.SecurityIdentifier ($bytes, 0)
            $sid.Translate([Security.Principal.NTAccount])
        }
    }

    The result should include the computer or domain name.