2

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)
    } 
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

2 Answers2

6

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

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
Clijsters
  • 4,031
  • 1
  • 27
  • 37
Peter
  • 1