[formatted] Remove azuread\user from localgroup administrators

Good afternoon (US Central)

I, nor Atera AI, can seem to get it correct… to Remove azuread\user from localgroup administrators

Trying to remove any azuread\user from the local group administrators, so they will be standard users.

This is the first code that doesn’t work

Define the local group name
$localGroupName = “administrators”

Define the domain name
$domainName = “azuread”

Get the members of the local group
$members = Get-LocalGroupMember -Group $localGroupName

Loop through each member and remove if it is an Azure AD user
foreach ($member in $members) {
if ($member.ObjectClass -eq “User” -and $member.Name.StartsWith("$domainName")) {
Remove-LocalGroupMember -Group $localGroupName -Member $member.Name
}
}

This is the error I get trying the first set of code

Get-LocalGroupMember : Failed to compare two elements in the array.
At localadmin.ps1:8 char:12

$members = Get-LocalGroupMember -Group $localGroupName
CategoryInfo : NotSpecified: (:slight_smile: [Get-LocalGroupMember], InvalidOperationException
FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand

.
.
.

That did not work, so I tried a second set of code, completely from scratch from the first set of code

Set the variable $adminGroup to the name of the administrators group
$adminGroup = “Administrators”

Get all members of the administrators group and filter out any that start with “LocalAdmin”
$members = Get-LocalGroupMember -Group $adminGroup | Where-Object {$_.Name -notlike “LocalAdmin”}

Loop through each member and remove them from the administrators group
foreach ($member in $members) {
Remove-LocalGroupMember -Group $adminGroup -Member $member.Name
}

Output a message indicating the script has completed
[lost this part of the code]

And now, I get this error

Get-LocalGroupMember : Failed to compare two elements in the array.
At localadmin.ps1:5 char:12

$members = Get-LocalGroupMember -Group $adminGroup | Where-Object {$_ …
CategoryInfo : NotSpecified: (:slight_smile: [Get-LocalGroupMember], InvalidOperationException
#NAME?```

Try changing to:

{$_.Name -notmatch 'LocalAdmin'}

Keep in mind, this is a ‘match’ so it will also trigger off an account named ‘userAddedLocalAdmin’

It the account name will always be “LocalAdmin”, you can use -ne

{$_.Name -ne 'LocalAdmin'}
2 Likes