PowerShell: Function to Get Group Members as a Bypass Orphanated SID Errors

Problem:

[TESTSERVER]: PS C:\Users\administrator> Get-LocalGroupMember 'Remote Desktop Users'

Get-LocalGroupMember : Failed to compare two elements in the array.
    + CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
    + FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand

[TESTSERVER]: PS C:\Users\administrator> Add-LocalGroupMember -group 'Remote Desktop Users' -member intranet\testuser
Add-LocalGroupMember : Principal intranet\testuser was not found.
    + CategoryInfo          : ObjectNotFound: (portal\nbsingh:String) [Add-LocalGroupMember], PrincipalNotFoundExcepti
   on
    + FullyQualifiedErrorId : PrincipalNotFound,Microsoft.PowerShell.Commands.AddLocalGroupMemberCommand

Workaround:

$servers = "localhost"
$groupName = 'Remote Desktop Users'

function getGroupMembers{
  param(
    $servers='localhost',
    $groupName='Administrators'
  )
  $members=@()
  foreach ($server in $servers){
      $group = [ADSI]"WinNT://$Server/$groupName"
      $groupMembers = @($group.Invoke('Members') | ForEach-Object {([ADSI]$_).path})
      $members+=$groupMembers
  }
  return $members
}

getGroupMembers $servers $groupName

Leave a Reply

Your email address will not be published. Required fields are marked *