How to Remove Domain Accounts from Local Administrators Group Using PowerShell?

0
13
Asked By TechyTaco123 On

I'm working on a script to remove domain accounts from the local Administrators group on Windows. I've been using PowerShell 5.1, but I've encountered some issues. While I can add and remove local and AzureAD users without a problem, I'm struggling when it comes to domain accounts. I utilize ADSI and .Net methods to read the accounts, as PowerShell functions for local groups in this version seem broken. Here's what I've tried so far:

1. I establish the necessary contexts with:
```powershell
Add-Type -AssemblyName System.DirectoryServices.AccountManagement -ErrorAction Stop
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, $env:COMPUTERNAME
```

2. When trying to remove a domain user from the group, I run this:
```powershell
$AdminGroup=[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context,'Administrators')
$UserSID='S-1-5-21-XXXXXXXXXX-XXXXXXXX-XXXXXXXXX-1137'
[void]$admingroup.members.Remove($context,$sidtype,$userSID)
$admingroup.save()
```

This works for local and orphaned accounts, but I get an error for domain accounts saying "No principal matching the specified parameters was found." Switching to using the SAM account name doesn't resolve the issue. Any suggestions for how I can successfully remove the domain users?

3 Answers

Answered By PowershellGuru77 On

You might want to consider if the devices are managed via Intune. If they are, you can adjust the Administrators group through an Endpoint Security policy instead of dealing with PowerShell. There are also some online resources to help with SID calculation for managing Entra groups. This way, you avoid messing with AzureAD identities directly.

HelpfulHarry99 -

It sounds like you're stuck in a hybrid setup then. Just keep in mind that your local domain setup might be interfering. Still, using Intune policies could streamline your process.

Answered By AdminAce88 On

What about leveraging Group Policy? You could clear all members of the group, which might be a more straightforward approach than trying to remove them one by one.

Answered By CodingWhiz91 On

Have you thought about upgrading to PowerShell 7? I've been using it for a while and haven't run into problems removing domain users. PowerShell 5.1 seems to have its quirks, especially with Active Directory users, but 7 might smooth things out for you.

SkepticalSteve88 -

That's not feasible for me right now, unfortunately. I’m locked into using 5.1 for this project.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.