Powershell: Removing users from a group called "test" if they are not an OU starting with "RBCO"

Powershell: Removing users from a  group called "test" if they are not an OU starting with "RBCO"
extsupportAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy LidbetterCommented:
Hi Extsupport

Give this a test...

$DistGroup = Test
$Members = Get-DistributionGroupMember $DistGroup | select distinguishedname, Name
foreach ($Member in $Members) {
	IF (-NOT(($member.distinguishedname.split(',')[1]).split('=')[1] -like "RBCO*")) {
			Remove-DistributionGroupMember -Identity $DistGroup -User $Member.Name
		}
	}

Open in new window


Regards

Guy
0
extsupportAuthor Commented:
It is not working it maybe because this is not a distribution group it is a security group

test : The term 'test' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path
is correct and try again.
At C:\Users\apanneto\Desktop\remove_inquisiq.ps1:1 char:14
+ $DistGroup = test
+              ~~~~
    + CategoryInfo          : ObjectNotFound: (test:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
Get-DistributionGroupMember : The term 'Get-DistributionGroupMember' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At C:\Users\apanneto\Desktop\remove_inquisiq.ps1:2 char:12
+ $Members = Get-DistributionGroupMember $DistGroup | select distinguishedname, Na ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-DistributionGroupMember:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
How about just inverting what has been done in http://www.experts-exchange.com/questions/28695401/Powershell-Adding-users-to-group-called-test-if-they-are-in-an-OU-starting-with-name-RBCO.html ? Use "-notlike" and "Remove-ADGroupMember" ...

However, both would not be effecient, as all users are processed, no matter if they are a member or not.
0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

extsupportAuthor Commented:
Is there something I can use that is more effecient?
0
extsupportAuthor Commented:
Import-module activedirectory
$Group = "test"
$Search = Get-ADOrganizationalUnit -Filter 'name -notlike "RBCO*"'

    ForEach ($OU in $Search)
            {

                $OU.DistinguishedName

                $User = Get-ADUser -Filter * -SearchBase $OU.DistinguishedName
                $User.sAMAccountName
                $User | Foreach { Remove-ADGroupMember -Identity $Group -Members $User.sAMAccountName }
       
}




I tried this and it did not remove the user from test group when they were not in an OU starting with RBCO.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
What are the figures of people not being in the OU and those which are?
0
extsupportAuthor Commented:
50/50
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Then it does not really matter, and the most simple and comprehensible approach should be used.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
In above code, are the users printed out as expected?
0
extsupportAuthor Commented:
Yes, is the user deletion from the group at the end of the process?
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
As soon as you see the user name on screen, the user should get removed from the group.
0
extsupportAuthor Commented:
It keeps prompting after every user. Anyway around this? Performing the operation "set" on target and it lists the path to the container.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
The script asks for confirmation?
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Yes, you need to add -Confirm $false to Remove-ADGroupMember to remove the confirmation prompt.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
The accepted answer is not the solution (in any regard) to this question. Did you accept the wrong one?
0
Guy LidbetterCommented:
I was in exchange brain mode when I wrote that ;-p

First error is because I neglected the "" around the distribution group name, second is because it was an exchange command...

By the way - AD Brain now - to sort it just change "DistributionGroupMember" in the script to "ADGroupMember" and it should work...  i.e.

Import-module activedirectory
$DistGroup = "Infrastructure"
$Members = Get-ADGroupMember $DistGroup | select distinguishedname, Name
foreach ($Member in $Members) {
	IF (-NOT(($member.distinguishedname.split(',')[1]).split('=')[1] -like "Domain*")) {
			Write-Host "Removing:" $Member.Name -ForegroundColor Yellow
			Remove-ADGroupMember -Identity $DistGroup -Members $Member.DistinguishedName -Confirm:$False -Whatif
		}
	Else {
		Write-Host "User" $Member.Name "is in a Domain OU" -ForegroundColor Green
	}
}

Open in new window


P.s. please remove the -Whatif from the script when you are ready to commit - otherwise it will just tell you what it's going to do...
Added some out put too... (don't know why I posted that script yesterday... it was terrible - obviously not enough coffee...)

Guy
0
extsupportAuthor Commented:
Guy,

This what I have. A test group with all users in RBCO OUs and intentionally added test users to OUs that don't start with RBCO.

Import-module activedirectory
$Group = "test"
$Members = Get-ADGroupMember $Group | select distinguishedname, Name
foreach ($Member in $Members) {
      IF (-NOT(($member.distinguishedname.split(',')[1]).split('=')[1] -like "RBCO*")) {
                  Write-Host "Removing:" $Member.Name -ForegroundColor Yellow
                  Remove-ADGroupMember -Identity $Group -Members $Member.DistinguishedName -Confirm:$False
            }
      Else {
            Write-Host "User" $Member.Name "is in a Domain OU" -ForegroundColor Green
      }
}
0
Guy LidbetterCommented:
That script will get all the users from the group and look at their distinguished name, from that decide whether they should be in the group.

This version of the script will only work if the user is directly in ANY "RBCO*" container. However; I can easily change the script to include users in any sub-trees as well if you need.

Have you tried the script yet and confirmed whether it would work as expected?

This one will not remove a user if it has RBCO anywhere in its Distinguished name...

$DistGroup = "test"
$Members = Get-ADGroupMember $DistGroup | select distinguishedname, Name
foreach ($Member in $Members) {
	IF ($member.distinguishedname -like "*RBCO*") {
			Write-Host "User" $Member.Name "is in a RBCO OU" -ForegroundColor Green
		}
	Else {
		Write-Host "Removing:" $Member.Name -ForegroundColor Yellow
		Remove-ADGroupMember -Identity $DistGroup -Members $Member.DistinguishedName -Confirm:$False -Whatif
	}
}

Open in new window

0
extsupportAuthor Commented:
Get-ADGroupMember : The operation returned because the timeout limit was exceeded.
At C:\Users\apanneto\Desktop\remove_inquisiq_test.ps1:3 char:12
+ $Members = Get-ADGroupMember $DistGroup | select distinguishedname, Name
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationTimeout: (test:ADGroup) [Get-ADGroupMember], TimeoutException
    + FullyQualifiedErrorId : The operation returned because the timeout limit was exceeded.,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember


I tried this and this is the outcome

Get-ADGroupMember : The operation returned because the timeout limit was exceeded.
At C:\Users\apanneto\Desktop\remove_inquisiq_test.ps1:3 char:12
+ $Members = Get-ADGroupMember $DistGroup | select distinguishedname, Name
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationTimeout: (test:ADGroup) [Get-ADGroupMember], TimeoutException
    + FullyQualifiedErrorId : The operation returned because the timeout limit was exceeded.,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
0
extsupportAuthor Commented:
This one works but it takes forever and a day

Import-module activedirectory
$Group = "test"
$Search = Get-ADOrganizationalUnit -Filter 'name -notlike "RBCO*"'

    ForEach ($OU in $Search)
            {

                $OU.DistinguishedName

                $User = Get-ADUser -Filter * -SearchBase $OU.DistinguishedName
                $User.sAMAccountName
                $User | Foreach { Remove-ADGroupMember -Identity $Group -Members $User.sAMAccountName -Confirm:$False }
       
}
0
Guy LidbetterCommented:
That last one takes forever because it parses every user in your domain that's not in the RBCO OU and tries to remove them whether they are in the group or not.

A timeout exception like that with my script is very odd... either there a thousands of members in that group or there is a DC issue.

You could try specifying the domain controller the search is run on by adding the option "-server DCNAME" as an example:

$DomainController = "<DCNAME>"
$DistGroup = "test"
$Members = Get-ADGroupMember $DistGroup -Server $DomainController | select distinguishedname, Name
foreach ($Member in $Members) {
	IF ($member.distinguishedname -like "*RBCO*") {
			Write-Host "User" $Member.Name "is in a RBCO OU" -ForegroundColor Green
		}
	Else {
		Write-Host "Removing:" $Member.Name -ForegroundColor Yellow
		Remove-ADGroupMember -Identity $DistGroup -Members $Member.DistinguishedName -Server $DomainController -Confirm:$False -Whatif
	}
}

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
extsupportAuthor Commented:
This script did work to show me which accounts need to be removed, but it did not remove them automatically. I would have to manually remove them.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Guy told you to remove the -whatif in http:#a40875662 to apply the changes.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.