ca9163d9
ca9163d9

Reputation: 29159

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)
    } 
}

Upvotes: 2

Views: 2820

Answers (2)

Peter
Peter

Reputation: 1

We have a similar issue where there are accounts from different domains on the computers and we need the domain back. Unfortunately the SID fetch doesn't work I think for local accounts and the domains the computer used to be joined to in some cases, so it didn't return all results.

This was the best solution I found for us:

Admin = $_.GetType().InvokeMember("AdsPath", 'GetProperty', $null, $_, $null)

will return results like

WinNT://#domain#/#account#

or WinNT://#domain of computer#/#computer-name#/#account#

for local accounts

$servers= get-content 'C:\temp\work\localadmins\serverlist_in.txt'
$output = 'C:\temp\work\localadmins\serverlist_out.csv' 
$results = @()

foreach($server in $servers)
{
    $admins = @()
    $group =[ADSI]"WinNT://$server/Administrators" 
    $members = @($group.psbase.Invoke("Members"))
    $members | foreach {
       $obj = new-object psobject -Property @{
           Server = $Server
           Admin = $_.GetType().InvokeMember("AdsPath", 'GetProperty', $null, $_, $null)
       }
       $admins += $obj
    } 
    $results += $admins
}
$results | Export-csv $Output -NoTypeInformation

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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.

Upvotes: 6

Related Questions