Skip to content

Get-LocalGroupMember - Failed to compare two elements in the array. #2996

Closed

Description

@ephos

It appears that if you have domain groups added to a local group and then move the server to a workgroup before removing them Get-LocalGroupMember no longer works and instead throws an exception 'Failed to compare two elements in the array.'. I am seeing this on Server 2016 Core, I have not tried on any other editions. I found this while building a server in one domain that needed to move to a different one.

Steps to reproduce

  • Join a Windows Server 2016 Core server to a domain.
  • Added 3 domain groups to the local administrators group.
  • Moved the server back into a workgroup.
  • Ran Get-LocalGroupMember -Group Administrators

I've reproduced this on two servers.

Expected behavior

It should return the group members as it would prior to moving to a workgroup and just display the unresolved SIDs for the old domain. Then ideally allow you to reference those unresolved SIDS for Remove-LocalGroupMember.

Actual behavior

Throws an exception.
2017-01-11_17-32-25

Environment data

> $PSVersionTable
PSVersion                      5.1.14393.206
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.206
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Activity

  1. mirichmo commented on Jan 11, 2017

    @mirichmo
    Member

    Rob (@ephos) This is an interesting issue. Can you please provide

    $Error[0] | fl * -force

    as well?

  2. ephos commented on Jan 12, 2017

    @ephos
    Author

    Mike Richmond (@mirichmo) here you go!

    > $Error[0] | fl * -Force
    
    
    writeErrorStream      : True
    PSMessageDetails      : 
    Exception             : System.InvalidOperationException: Failed to compare two elements in the array. ---> 
                            System.NullReferenceException: Object reference not set to an instance of an object.
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.<>c.<ProcessesMembership>b_
                            _20_0(LocalPrincipal p1, LocalPrincipal p2)
                               at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 
                            comparer, Int32 a, Int32 b)
                               at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 
                            left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
                               at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 
                            length, IComparer`1 comparer)
                               --- End of inner exception stack trace ---
                               at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 
                            length, IComparer`1 comparer)
                               at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
                               at System.Collections.Generic.List`1.Sort(Comparison`1 comparison)
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.ProcessesMembership(IEnumer
                            able`1 membership)
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.ProcessRecord()
    TargetObject          : 
    CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
    FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand
    ErrorDetails          : 
    InvocationInfo        : System.Management.Automation.InvocationInfo
    ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
    PipelineIterationInfo : {0, 1}
    
  3. mirichmo commented on Jan 12, 2017

    @mirichmo
    Member

    Thanks for the info

  4. iSazonov commented on Jan 12, 2017

    @iSazonov
    Collaborator

    It's work well on Windows 10 :

    Name                           Value
    ----                           -----
    CLRVersion
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    GitCommitId                    v6.0.0-alpha.14-28-geef6ed0584ba62e232f95668ad25d277d2137efc-dirty
    SerializationVersion           1.1.0.1
    PSRemotingProtocolVersion      2.3
    PSEdition                      Core
    WSManStackVersion              3.0
    BuildVersion                   3.0.0.0
    PSVersion                      6.0.0-alpha
    
  5. ssylvan commented on Jan 13, 2017

    @ssylvan

    I am also hitting this issue, any workarounds?

  6. iSazonov commented on Jan 13, 2017

    @iSazonov
    Collaborator

    Sebastian Sylvan (@ssylvan) Can you confirm that the problem is on Windows Server 2016 Core server only.

  7. ssylvan commented on Jan 13, 2017

    @ssylvan
  8. iSazonov commented on Jan 13, 2017

    @iSazonov
    Collaborator

    Sebastian Sylvan (@ssylvan) Thanks for the clarification.

  9. itisbrendan commented on Jan 31, 2017

    @itisbrendan

    Hello, I'm seeing this error raised as well. Windows 10 Pro

    PS C:\> [System.Environment]::OSVersion.Version
    
    Major  Minor  Build  Revision
    -----  -----  -----  --------
    10     0      14393  0
    
  10. iSazonov commented on Feb 1, 2017

    @iSazonov
    Collaborator

    ItsBrendan (@itisbrendan) Thanks for confirmation!

  11. OraDotNetDev commented on Feb 2, 2017

    @OraDotNetDev

    Workaround here

    Same experience in Windows 7 Enterprise and exactly the same Error details as Rob (@ephos)

    Major  Minor  Build  Revision
    -----  -----  -----  --------
    6      1      7601   65536
    
    
    PS C:\> $PSVersionTable
    
    Name                           Value
    ----                           -----
    PSVersion                      5.1.14409.1005
    PSEdition                      Desktop
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    BuildVersion                   10.0.14409.1005
    CLRVersion                     4.0.30319.42000
    WSManStackVersion              3.0
    PSRemotingProtocolVersion      2.3
    SerializationVersion           1.1.0.1
    
  12. PwshPally commented on Mar 6, 2017

    @PwshPally

    I'm getting the same on Win10 joined to Azure AD. This PC has never been part of a traditional Active Directory.

    PS C:\Users\SteveMahoney> $PSVersionTable
    
    Name                           Value                                                                                                                            
    ----                           -----                                                                                                                            
    PSVersion                      5.1.14393.693                                                                                                                    
    PSEdition                      Desktop                                                                                                                          
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                          
    BuildVersion                   10.0.14393.693                                                                                                                   
    CLRVersion                     4.0.30319.42000                                                                                                                  
    WSManStackVersion              3.0                                                                                                                              
    PSRemotingProtocolVersion      2.3                                                                                                                              
    SerializationVersion           1.1.0.1 
    
    PS C:\Users\SteveMahoney> Get-LocalGroupMember -Group "Administrators"
    Get-LocalGroupMember : Failed to compare two elements in the array.
    At line:1 char:1
    + Get-LocalGroupMember -Group "Administrators"
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
        + FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand
     
    
    PS C:\Users\SteveMahoney> $Error[0] | fl * -force
    
    
    writeErrorStream      : True
    PSMessageDetails      : 
    Exception             : System.InvalidOperationException: Failed to compare two elements in the array. ---> System.NullReferenceException: Object reference not 
                            set to an instance of an object.
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.<>c.<ProcessesMembership>b__20_0(LocalPrincipal p1, LocalPrincipal p2)
                               at System.Collections.Generic.ArraySortHelper`1.InsertionSort(T[] keys, Int32 lo, Int32 hi, IComparer`1 comparer)
                               at System.Collections.Generic.ArraySortHelper`1.IntrospectiveSort(T[] keys, Int32 left, Int32 length, IComparer`1 comparer)
                               at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
                               --- End of inner exception stack trace ---
                               at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
                               at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
                               at System.Collections.Generic.List`1.Sort(Comparison`1 comparison)
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.ProcessesMembership(IEnumerable`1 membership)
                               at Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand.ProcessRecord()
    TargetObject          : 
    CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
    FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand
    ErrorDetails          : 
    InvocationInfo        : System.Management.Automation.InvocationInfo
    ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
    PipelineIterationInfo : {0, 1}
    
  13. fullenw1 commented on May 4, 2017

    @fullenw1

    Same issue on Windows 2008 R2 and 2012 R2.

  14. 156 remaining items

  15. alexipeck commented on Jan 24, 2024

    @alexipeck

    If anyone is looking for a workaround where getting an array of usernames is the goal and are fine with the old "net localgroup administrators", keeping in mind that this won't provide you with the user object, here are a couple of implementations:

    Get all users in the group:
    $(net localgroup administrators) | Where-Object { -not ($_ -match '^-+$|^The command completed successfully.$|^Members$|^Alias name\s+administrators$|^Comment\s+Administrators have complete and unrestricted access to the computer/domain$|^$') -and $_.Trim() -ne '' }

    Get all users minus a few matching a regex filter, adding pipe | separated usernames (e.g, "Administrator") or more complex filters (e.g, ".*Domain Admins"):
    $(net localgroup administrators) | Where-Object { -not ($_ -match 'Administrator|.*Domain Admins|^-+$|^The command completed successfully.$|^Members$|^Alias name\s+administrators$|^Comment\s+Administrators have complete and unrestricted access to the computer/domain$|^$') -and $_.Trim() -ne '' }

  16. emilwojcik93 commented on Feb 10, 2024

    @emilwojcik93

    Issue

    I was able to make an workaround for this issue because it's still exists in:

    OSVersion                     : 2009
    OSEdition                     : Microsoft Windows 11 Enterprise
    OSBuild                       : 22621.3007
    CurrentInstalledUpdate        : January 9, 2024 - KB5034123 (OS Builds 22621.3007 and 22631.3007)

    Example:

    > Get-LocalGroupMember -Group "Administrators"
    Get-LocalGroupMember : Failed to compare two elements in the array.
    At line:1 char:1
    + Get-LocalGroupMember -Group "Administrators"
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
        + FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand

    There is an .NET method WindowsIdentity.GetCurrent Method

    Workaround Script:

    param(
        [Parameter(Mandatory=$true, Position=0)]
        [Alias("g")]
        [string]$GroupName
    )
    
    function CheckGroupMembership {
        param([string]$groupName)
    
        $id = [Security.Principal.WindowsIdentity]::GetCurrent()
        $groups = $id.Groups | foreach-object {$_.Translate([Security.Principal.NTAccount])}
    
        $isMember = ($groups.Value | Where-Object { $_.Split('\')[-1] -eq $groupName } | Measure-Object).Count -gt 0
    
        if ($isMember) {
            Write-Host "User: `"$($id.Name)`" is a member of a group ending with `"$groupName`"."
        } else {
            Write-Host "User: `"$($id.Name)`" is not a member of any group ending with `"$groupName`"."
        }
    }
    
    CheckGroupMembership -groupName $GroupName

    Examples:

    Administrators:

    > .\autosetup\deps\test-group.ps1 -groupName "Administrators"
    User: "XXXXXX" is not a member of any group ending with "Administrators".

    Users:

    > .\autosetup\deps\test-group.ps1 -groupName "Users"
    User: "XXXXXX" is a member of a group ending with "Users".

    Further reading

  17. subcat commented on Apr 16, 2024

    @subcat

    if anyone is still getting this, i found that if an unknown/deleted user exists in the queried group, the command fails. you need to remove the SID of the unknown / non existing user from the group. this resolved the issue for me.

  18. 3vi1 commented on Apr 16, 2024

    @3vi1

    Yes. I gave up on it and had to go with ADSI instead. I've got thousands of servers with plenty of deleted accounts from retired employees and former contractors that the owners put in local groups over the last 20 years (trying to clean that up separately; I needed something that works now).

  19. iSazonov commented on May 16, 2024

    @iSazonov
    Collaborator

    The bug was fixed in PowerShell 7.4+ compatible (unofficial) version of the Microsoft.PowerShell.LocalAccounts module
    https://github.com/iSazonov/LocalAccounts-MS/tree/v7.0.0-Release.1

    GitHub
    Contribute to iSazonov/LocalAccounts-MS development by creating an account on GitHub.
  20. iSazonov commented on Jul 9, 2024

    @iSazonov
    Collaborator

    Fixed in community module https://www.powershellgallery.com/packages/LocalAccounts

    Provides cmdlets to work with local users and local groups
  21. celticguy42 commented on Sep 29, 2024

    @celticguy42

    I've experienced this a few times. Each time it's been due to a deleted account being part of the group in question. Obviously, that shouldn't generate this issue, but in my case it does.

    In Computer Management, I went in to the group, and in the Membership tab, there was a SID. I simply removed the SID.

  22. zxcvxzcv-johndoe commented on Feb 10, 2025

    @zxcvxzcv-johndoe

    I've experienced this a few times. Each time it's been due to a deleted account being part of the group in question. Obviously, that shouldn't generate this issue, but in my case it does.

    In Computer Management, I went in to the group, and in the Membership tab, there was a SID. I simply removed the SID.

    Thank you! Removing the sid-entry from the Administrators group even solved our Exchange HealthChecker.ps1's error message
    "Exchange Server Membership: Failed
    Unable to determine Local System Membership as the results were blank." which was caused by failing Get-LocalGroupMember -Group "Administrators" command

  23. 3vi1 commented on Feb 10, 2025

    @3vi1

    Why is this closed when it still affects everyone who has groups containing unresolvable GUIDs? Unless you're using a pristine test lab, you're going to run into this problem at some point.

    My company has 10's of thousands of AD accounts, and developer/server owners just to assign individual AD accounts for contractors to specific server groups (even when it's against standards). Those contractors leave. It would be nice if the PS command behaved in a reasonable manner when this occurs.

  24. mgreenegit commented on Feb 10, 2025

    @mgreenegit
    Member

    Why is this closed when it still affects everyone who has groups containing unresolvable GUIDs? Unless you're using a pristine test lab, you're going to run into this problem at some point.

    In which release of Windows Server are you reproducing this issue?

  25. GoodThings2Life commented on Feb 11, 2025

    @GoodThings2Life

    Why is this closed when it still affects everyone who has groups containing unresolvable GUIDs? Unless you're using a pristine test lab, you're going to run into this problem at some point.

    In which release of Windows Server are you reproducing this issue?

    Literally all versions of Windows including latest supported releases. This is a long-standing issue.

  26. zxcvxzcv-johndoe commented on Feb 11, 2025

    @zxcvxzcv-johndoe

    Why is this closed when it still affects everyone who has groups containing unresolvable GUIDs? Unless you're using a pristine test lab, you're going to run into this problem at some point.

    In which release of Windows Server are you reproducing this issue?

    Well my post yesterday was about "Windows Server 2019 Standard Edition (10.0.17763.6775) with PSVersion 5.1.17763.6766" so that's with the latest updates and using GUI (if that makes difference).

  27. mgreenegit commented on Feb 11, 2025

    @mgreenegit
    Member

    Confirmed I cannot reproduce the issue on Server 2025.

    Image

    GoodThings2Life, Jesse Litton (@3vi1), can you confirm your version of Windows Server?

  28. 3vi1 commented on Feb 11, 2025

    @3vi1

    Confirmed I cannot reproduce the issue on Server 2025.

    Image

    @GoodThings2Life, @3vi1, can you confirm your version of Windows Server?

    I have 3000+ different windows servers in 14 domains running everything from 2008 (hardened legacy, being decommed) to 2022. I can't fix this by "simply upgrading" to 2025, nor will most companies of any size.

  29. PhilippeMP commented on Apr 11, 2025

    @PhilippeMP

    Use ADSI

    function Get-AdsiLocalGroupMember() {
        [CmdletBinding()]
        Param(
            [string]$Group
        )
    
        $AdsiGroup  = [ADSI]"WinNT://$env:COMPUTERNAME/$Group,group"
    
        $AdsiGroup.Members() | ForEach-Object {
            $cobj = ([adsi]$_).PSBase
            $adsPath = $cobj.InvokeGet("ADsPath")
            $Domain  = Split-Path (Split-Path $adsPath -Parent) -Leaf
        
            [PSCustomObject]@{
                ComputerName = $env:COMPUTERNAME
                GroupName    = $Group
                Name         = $cobj.InvokeGet("Name")
                Class        = $cobj.InvokeGet("Class")
                Domain       = $Domain
                ADsPath      = $adsPath
            }
        } | Sort-Object Name
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-BugIssue has been identified as a bug in the productResolution-ExternalThe issue is caused by external component(s).WG-Cmdletsgeneral cmdlet issues

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions