Powershell: Get-LocalGroupMember - Failed to compare two elements in the array.

Created on 11 Jan 2017  Â·  65Comments  Â·  Source: PowerShell/PowerShell

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

Area-Cmdlets Issue-Bug

Most helpful comment

@Hicsy after we have a fix in PSCore6, we can consider backporting it to Windows PowerShell 5.1.

All 65 comments

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

$Error[0] | fl * -force

as well?

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

Thanks for the info

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

I am also hitting this issue, any workarounds?

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

I'm seeing it on windows 10 on a surface book.

On Thu, Jan 12, 2017 at 10:46 PM, Ilya notifications@github.com wrote:

@ssylvan https://github.com/ssylvan Can you confirm that the problem is
on Windows Server 2016 Core server only.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/PowerShell/PowerShell/issues/2996#issuecomment-272373455,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABTVpweK9qalpKLeTK1yx5TwZ7csJI-Mks5rRx3ggaJpZM4LhJ0X
.

--
Sebastian Sylvan

@ssylvan Thanks for the clarification.

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

@itisbrendan Thanks for confirmation!

Workaround here

Same experience in Windows 7 Enterprise and exactly the same Error details as @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

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}

Same issue on Windows 2008 R2 and 2012 R2.

I've had a bit of a poke around and a chat and some help from faustonascimento on IRC. This code will reproduce the problem:

Import-Module Microsoft.PowerShell.LocalAccounts
Add-Type -ReferencedAssemblies ([PowerShell].Assembly.Location), ([Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand].Assembly.Location) -TypeDefinition '
using System;
using System.Collections.Generic;
using System.Security.Principal;
using Microsoft.PowerShell.Commands;

public class Test
{
    public static IEnumerable<LocalPrincipal> Get()
    {
        List<LocalPrincipal> rv = new List<LocalPrincipal>();

        LocalPrincipal principal = new LocalPrincipal(Environment.UserName);
        principal.SID = (SecurityIdentifier)(new NTAccount(Environment.UserName)).Translate(typeof(SecurityIdentifier));
        rv.Add(principal);

        // https://github.com/PowerShell/PowerShell/blob/1462ac300bc5e4a20f0360b428de1cb1de4eaba4/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs#L2813
        rv.Add(null);

        rv.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.CurrentCultureIgnoreCase));
        return rv;
    }
}
'
[Test]::Get()

The problem appears to be caused by the null return from the MakeLocalPrincipalObject method:

https://github.com/PowerShell/PowerShell/blob/1462ac300bc5e4a20f0360b428de1cb1de4eaba4/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs#L2810

The null value is being pushed to MakeLocalPrincipalObject because an invalid SID will cause a name lookup failure from Win32.LookupAccountSid. This method explicitly returns null when the error code ERROR_NONE_MAPPED (1332) is set.

This value is not filtered out and ends up being added to the rv collection which subsequently fails on Sort.

It can be argued that this value should be filtered out, as the null value is not useful. For example, by inserting:

rv = rv.Where(x => x != null).ToList();

Returning the invalid entry is a deep(er) change to the GetGroupMembers method. This would potentially be useful as it may allow these commands to fix the problem (if it is such) rather than just ignoring the condition. Achievable by speculatively replacing the yield return with line with the following:

var sid = new SecurityIdentifier(idArray[i]);
AccountInfo info = LookupAccountInfo(sid);
if (info == null)
{
    info = new AccountInfo { Sid = sid };
}
yield return MakeLocalPrincipalObject(info);

The LookupAccountInfo method is shared by most of the other commands, changing its behaviour would be intrusive. GetGroupMembers only appears to be used by Get-LocalGroupMember.

Chris

I think in general this makes sense. The only other method that calls MakeLocalPrincipalObject checks for a null return from LookupAccountInfo and throws an exception.

I'm curious about why we would be getting an invalid SID in the first place. There are two overloads for the GetGroupMembers method---one takes a group name and the other takes a group SID. They do their queries for group membership in different ways (Net API _vs._ SAM API). Do we know whether the null comes from one of these or the other, or both?

I only see one overload for GetGroupMembers in the source code? There are two overloads for GetLocalGroupMembers, both call GetGroupMembers with a SID.

It seems the only way to recreate this is described in the first post. A machine must be added to the domain, a member added, then the machine removed from the domain. Using a local user is not sufficient to recreate the problem. I'm not at liberty to test such things at the moment although it will need to be tested after the code has been changed.

Oops. Sorry, you're right. I was looking at an experimental version I'd forgotten about.

After re-reading the original description and looking at things again, the whole thing makes more sense to me and I think your solution is the correct one. There would need to be an additional minor change elsewhere to get the SID to be displayed in the output in place of the name, and there would be no way (I think) to correctly determine the ObjectClass.

Sorry for the noise.

Of course, all this kinda depends on the LocalAccounts cmdlets getting back into the build once they no longer use the SAM API.

Any update?
ALL PC's at work can't use get-localgroupmembers due to being Azure-AD connected.

  1. Create an O365/AzureAD tenant, and add a user. Can be just intune, but most commonly EMS pack... and soon EVERY customer who buys Microsoft 365 business/enterprise suite (Windows 10 Enterprise, EMS, Office 365) will be affected.
  2. Start a NEW computer. Anything Windows 10. Otherwise just spool up a new VM with a fresh Windows 10 installation. During normal OOBE setup it will ask the user to sign into Microsoft.
  3. Sign into the work account created in step 1.
  4. Windows will add this user account to "Administrators" localgroup automatically due to there not being an active local administrator account set up.

Likely due to there being an AzureAD account - this powershell cmdlet always crashes

PS C:\WINDOWS\system32> net localgroup administrators
Alias name     administrators
Comment        Administrators have complete and unrestricted access to the computer/domain

Members

-------------------------------------------------------------------------------
Administrator
AzureAD\TestO365Account
The command completed successfully.
PS C:\WINDOWS\system32> Get-LocalGroupMember administrators
Get-LocalGroupMember : Failed to compare two elements in the array.
At line:1 char:1
+ Get-LocalGroupMember administrators
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-LocalGroupMember], InvalidOperationException
    + FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand

Diagnostics:

PS C:\WINDOWS\system32> $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(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}


PS C:\WINDOWS\system32> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17046.1000
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17046.1000
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

/cc @SteveL-MSFT Azure-AD scenario failed.

I haven't been rushing to make a PR as this will only affect PowerShell 6 builds where it's currently not operational (and I'm rather busy at the moment).

It would be rather nice to stream this out as a standalone module, but even if it is, that won't make it immediately available to anyone.

@Hicsy after we have a fix in PSCore6, we can consider backporting it to Windows PowerShell 5.1.

@SteveL-MSFT I also would like to see that fix in 5.1 since im running into the same issue.

Running windows 2012 R2


PS C:\> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
6      3      9600   0

Name                           Value                                                                                   
----                           -----                                                                                   
PSVersion                      5.1.14409.1012                                                                          
PSEdition                      Desktop                                                                                 
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                 
BuildVersion                   10.0.14409.1012                                                                         
CLRVersion                     4.0.30319.42000                                                                         
WSManStackVersion              3.0                                                                                     
PSRemotingProtocolVersion      2.3                                                                                     
SerializationVersion           1.1.0.1                                                                                 




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

FFS.

Are there any updates on this?

Yes, please fix this if you can.

On Wed, May 9, 2018, 1:50 PM neomancipator notifications@github.com wrote:

Are there any updates on this?

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/PowerShell/PowerShell/issues/2996#issuecomment-387820740,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AYSeDTlJbiLHL2YvQ5f0k4W_4pNtYqfsks5twyxhgaJpZM4LhJ0X
.

@SteveL-MSFT

after we have a fix in PSCore6, we can consider backporting it to Windows PowerShell 5.1.

Should we enable the module on Windows?

@iSazonov we can't enable the module until we have a solution that uses public apis. Since PSCore6 ships outside of Windows, we must only use public apis.

Since this is impacting people, I'll see about making a change in WPS5.1, but it'll only be available on newest releases of Windows.

still seeing this issue

Can we migrate to System.DirectoryServices.AccountManagement?

@SteveL-MSFT Is this right way? We have the API in Windows Compatibility Pack.

@iSazonov I'm not knowledgeable enough about that namespace to say whether that's the right direction. It seems that if there's leftover data from the domain which is no longer relevant to the local system, it may be ok to add the synthetic account to inform user there are accounts that cannot be resolved.

Just FYI, I had been looking into using the Net* functions from the Windows API to implement this. Presumably that would remain Windows only, right?

@jeffbi yes, this would remain Windows only

@PowerShell/powershell-committee discussed this, this module is not part of PSCore6 at this time. Porting it to use the new DirectoryServices APIs may be ok, but outside the scope of what we reviewed.

I was able to work around the PowerShell bug issue by fixing the root of the problem. I found that this error was raised because I had a few corrupt/unknown users in the Group I was querying. I deleted the old entries in the Local Users and Groups (lusrmgr.msc) and the command completed with success.

image

Confirming nuttingd discoveries. Tested on 7 serveres, version 2012, 2012R2 and 2016.
Good job!

Can confirm nuttingd's procedure resolves the issue.

Ok than this is a workaround and the cmdlet still needs to be able to handle this situation.

This will also be a problem if you have a deleted domain user or group and if you have a foreign SID from a 1-way trust. We definitely need the cmdlet to be able to output the SID so that old principals can be cleaned up and foreign principals can be reported accurately.

This is also a big issue for the organisation that I am in and whats worse is that I am getting errors through DSC and puppet due to this cmdlet not being able to handle deleted and/or disabled users from AD.

are there any further updates on fixing this issue?

Can confirm this is definitely still an issue. No-one has posted a workaround that didn't involve 'fixing' the underlying issue, directly here though, so here's mine.

I was zipping the results so I wanted the content basically the same whether it worked the 'easy way' or with the workaround. It's sort of nice because now there's a warning when an invalid SID is on a server.

```$zipfilepath = $ZipPath
New-Item -ItemType Directory $zipfilepath -ErrorAction SilentlyContinue -Verbose | Out-Null

$machinename = $env:COMPUTERNAME
try{
$Admins = Get-LocalGroupMember "Administrators"
}
catch{
Write-Warning "Invalid SID or other issue detected. Remove it!!"
$query="Associators of {Win32_Group.Domain='$machinename',Name='Administrators'} where Role=GroupComponent"
$Admins = get-wmiobject -query $query -ComputerName $machinename | Select @{L='Name';E={$_.Caption}},Caption,@{L='ObjectClass';E={$_.__CLASS}} } $Admins |
Select Name,@{L='Type';E={$_.ObjectClass}} | Export-Csv -Path "$zipfilepath\localadmin-$machinename.csv" -NoTypeInformation
-Verbose -Force
```

This may not be a foreign SID. If the machine is AAD joined, the AAD Global Administrators role SID and the AAD Device (company) Administrators role SIDs will appear in the local admin group.

If necessary, you can use this as a psuedo-workaround:
$adminGroup.psbase.Invoke("Members")|ForEach-Object -Process {$_.GetType().InvokeMember("Name", 'GetProperty',$null, $_, $null)}

Two years later..... Ugh.

On Thu, Aug 15, 2019, 9:35 PM Scott Kissel notifications@github.com wrote:

This may not be a foreign SID. If the machine is AAD joined, the AAD
Global Administrators role SID and the AAD Device (company) Administrators
role SIDs will appear in the local admin group.

If necessary, you can use this as a psuedo-workaround:
$adminGroup.psbase.Invoke("Members")|ForEach-Object -Process
{$_.GetType().InvokeMember("Name", 'GetProperty',$null, $_, $null)}

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/PowerShell/PowerShell/issues/2996?email_source=notifications&email_token=AGCJ4DKQEP4UCSAZLJEES3TQEX76JA5CNFSM4C4ETUL2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD4NNPGY#issuecomment-521852827,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AGCJ4DN45UCPH34O6XOIXBDQEX76JANCNFSM4C4ETULQ
.

Yep. On Insider Preview 18936 and PS 5.1.18936.1000 no AD or AzureAD, just workgroup. Still getting this error. :(

I get this error anytime the orphaned SID is referred to in the Security Group.

Looking at this many feedback I hope to continue #9926 (and create RFC)
/cc @SteveL-MSFT for information

None of the machines I have encountered this on were ever joined to a domain, and do not have any orphaned SIDs in local groups. The latest was a VM I built from scratch using a Win10 1903 iso.

Happening for me as well. Group 'Users' has an unassociated SID. Attempting Get-LocalGroupMember on this group returns:

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

Blocking an urgent audit. WMI workaround has its own quirks but is apparently the best we can do until this is fixed.

$Error[0] | fl * -force` returns:

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 4
PipelineIterationInfo : {0, 1}
Major  Minor  Build  Revision
-----  -----  -----  --------
10     0      16299  0       

$PSVersionTable returns:

Name                           Value                                                                                                                                                    
----                           -----                                                                                                                                                    
PSVersion                      5.1.16299.1146                                                                                                                                           
PSEdition                      Desktop                                                                                                                                                  
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                  
BuildVersion                   10.0.16299.1146                                                                                                                                          
CLRVersion                     4.0.30319.42000                                                                                                                                          
WSManStackVersion              3.0                                                                                                                                                      
PSRemotingProtocolVersion      2.3                                                                                                                                                      
SerializationVersion           1.1.0.1       

This is also a big issue for the organisation that I am in and whats worse is that I am getting errors through DSC and puppet due to this cmdlet not being able to handle deleted and/or disabled users from AD.

are there any further updates on fixing this issue?

I created a Puppet Task to remove the unresolvable sid issue I was having.

https://github.com/ffalor/ffalor-resolve_sid

Will be putting it on the forge in a little bit once I go through and make it a little cleaner. We had hundreds of servers failing in Puppet due to the SID issue, and I was able to fix them all in a few seconds with this task.

GitHub
Puppet Task to remove unresolvable SIDs from Windows - ffalor/ffalor-resolve_sid

Uploaded to forge
https://forge.puppet.com/ffalor/resolve_sid

I know it's not quite the same, but you can parse text out of the following command to get local group membership in place of this command.
"net localgroup [localgroupname]"
ex:
net localgroup administrators
Windows just can't seem to kill their old console =/

Found a script which fixes the problematic SAM-Entry here
https://administrator.de/content/detail.php?id=538099
It removes non resolvable SIDs from the hex binary for the administrators group membership. After running the script the PS command works again. So it's not a Powershell problem, it's a Windows bug which leaves old sid entries in the SAM. First script is to manually remove specific SIDs, the second automatically removes all non resolvable SIDs from the entry.

Administrator.de
Moin Kollegen. Wer schon auf Betriebstemperatur ist und ein forderndes Problem sucht - Mit dem Powershell-Kommando bekommt man normalerweise die Mitglieder der lokalen Admingruppe angezeigt. Hat man d.

I'd just like to confirm that I'm running into this problem when I try to use Get-LocalGroupMember and my target group has unresolved SIDs in them. Most likely the AD objects no longer exist.

I think this is the best workaround to being able to enumerate all members of a group even if there are unresolved SIDs.
foreach ($group in Get-LocalGroup ) {
$group = [ADSI]"WinNT://$env:COMPUTERNAME/$group"
$group_members = @($group.Invoke('Members') | % {([adsi]$_).path})
$group_members
}

Issue from january 2017, still not resolved in Windows 10, not even 20H1 (19041.172).
GG Microsoft.

Thanks for the code @passbt

@o-l-a-v The code is not in the repo. It is Windows component. But Windows PowerShell is frozen - only PowerShell Core can progress. So it is zugzwang :-(
We could migrate to new module but it is a breaking change.

@o-l-a-v The code is not in the repo. It is Windows component. But Windows PowerShell is frozen - only PowerShell Core can progress. So it is zugzwang :-(
We could migrate to new module but it is a breaking change.

Roger that, makes sense. But unless PS Core becomes default for Windows very soon, this is a very basic PS management ability that really should work out of the box on any Windows edition and version IMHO. How Ms fixes or mitigates that functionality is not important. The only important thing is that it should work out of the box, or removed as it can cause serious issues.

Please use Windows feedback tool to vote for the fix.

Mark this issue to be re-reviewed by the committee.
Get-LocalGroupMember is not part of the PowerShell repo, but given that the Microsoft.PowerShell.LocalAccount module is marked as CompatiblePSEdition = @('Desktop', 'Core') , people will use it in PowerShell 7 and run into the same issue. So we probably should push for a fix in Windows.

My first plan was to rewrite the module from scratch but today I look the code and found that we can port it to public API (AccountManagement) with minimal breaking changes (I don't know how many breaking changes will be, while I only see exception handling).
I hope to pull a draft in hours.

That is great news Ilya! I look forward to seeing this and will for sure test it when it hits a daily build.

For Windows PowerShell 5.1, we've started a conversation with the team that owns servicing it to see if they are willing to make the fix.

@doctordns You can test. Specially in domain environment. That would be great if you made a new test file for domain scenario.

For those who run into this problem, and just need a workaround, here is a snippet that should give you what you need:
$localAdminGroupWmi = Get-WMIObject Win32_Group -Filter "Name='Administrators'" $localAdminGroupWmi.GetRelated("Win32_UserAccount")

This will subsequently list all User Accounts that are members of the Administrators group. Please note that "Administrators" is not language agnostic. For a Windows PC with Norwegian language, it would be "Administratorer" for instance.

If you need to check if a specific account is member of the admin group, you could then do something like this:

if($null -eq ($localAdminGroupWmi.GetRelated("Win32_UserAccount") | Where-Object -Property Caption -Like -Value "*\AdminAccount")) { Write-Host "No account with name "AdminAccount" found in the Administators group" }

@SteveL-MSFT - any updates on this? Our organization is seeing this same behavior after migrating to a hybrid-joined model. PS 5.1 is still the lowest common denominator for infrastructure and InfoSec operations in many corporations. 😄

@Rusty-Shackleford The module is not in the repo, it is Windows component. So please use Windows Feedback tool and other channels to retort the issue to Windows team.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JohnLBevan picture JohnLBevan  Â·  3Comments

alx9r picture alx9r  Â·  3Comments

rudolfvesely picture rudolfvesely  Â·  3Comments

HumanEquivalentUnit picture HumanEquivalentUnit  Â·  3Comments

rkeithhill picture rkeithhill  Â·  3Comments