Home > Software engineering >  Powershell to remove-adgroupmembers listed in a text file where the group for them to be removed fro
Powershell to remove-adgroupmembers listed in a text file where the group for them to be removed fro

Time:04-28

I'm looking for a way to remove AD computers that are listed in a text file from any AD groups they might be in, within the same OU. For example, the text file contains:
Computer1$
Computer2$
Computer3$

The groups those three computers might appear in are:
Group1
Group2
Group3

I found this on StackOverflow from 2016 from the title "PowerShell - Remove-ADGroupMember - Locking my admin account" and edited for me:
Get-ADGroup -filter 'name -like "Group*"' | Remove-ADGroupMember -Members "Computer3$"
This works fine to remove "Computer3$! But when I try to replace "Computer3$" with my variable in a Foreach, it breaks. Here's my code:

$Comps = Get-Content "C:\Users\Administrator\Desktop\Complist.txt"
foreach ($comp in $comps) {
Get-ADGroup -filter 'name -like "Group*"' | Remove-ADGroupMember -Members "$Comps"
}

and errors with:

Remove-ADGroupMember : Cannot find an object with identity: 'Computer1$
Computer2$ Computer3$' under: 'DC=Domain,DC=local'.
At line:3 char:53
  ... name -like "Group*"' | Remove-ADGroupMember -Members "$Comps"
                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (Computer1...mputer3$:ADP 
   rincipal) [Remove-ADGroupMember], ADIdentityNotFoundException
      FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.Ac 
   tiveDirectory.Management.Commands.RemoveADGroupMember

Any help would be much appreciated, thank you in advance.

CodePudding user response:

$Comps = Get-Content "C:\Users\Administrator\Desktop\Complist.txt"
foreach ($comp in $comps) {
Get-ADGroup -filter 'name -like "Group*"' | Remove-ADGroupMember -Members "$comp"
}

You were referencing $comps (the group of objects) instead of $comp (the object) inside your loop.

Import-Module -Name ActiveDirectory
$listofcomputers = Get-Content -Path "$env:HOMEDRIVE\Users\Administrator\Desktop\Complist.txt"

foreach ($computer in $listofcomputers) {
    Get-ADGroup -Filter 'name -like "Group*"' | Remove-ADGroupMember -Members ('{0}' -f $computer)
}

Better variable naming would help here.

  • Related