PowerShell - add an exclusion into Remove-ADGroupMember command? - powershell

When somebody leaves my organization, we remove all AD group memberships apart from the PrimaryGroup which is Domain Users. We often process these in batches, so pull the affected usernames from a CSV file.
I have the following code, and while it does the job of deleting all group memberships, I get an error for each user:
The user cannot be removed from a group because the group is currently the user's primary group
Whilst it does the job, how can I "clean up" the process to avoid this message each time? Is there a way to exclude Domain Users from the groups it removes the user from, or should I do this another way?
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
Get-ADPrincipalGroupMembership -identity $user.username | foreach {Remove-ADGroupMember $_ -Members $user.username -Confirm:$false}
}

You can use Where-Object for filtering those groups that are not in an array of groups to exclude. In case you only want to filter for 1 specific group, you would use -NE instead of -NotIn in below example.
$groupToExclude = 'Domain Users', 'someOtherGroup'
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
try {
Get-ADPrincipalGroupMembership -Identity $user.username |
Where-Object Name -NotIn $groupToExclude |
Remove-ADGroupMember -Members $user.username -Confirm:$false
}
catch {
Write-Warning $_.Exception.Message
}
}

If you get the ADUser object before the ADGroup memberships, you can get the PrimaryGroup of the user and ensure that the list of groups to remove from are not its PrimaryGroup:
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
$primaryGroup = ( Get-ADUser $user.UserName -Properties PrimaryGroup ).PrimaryGroup
Get-ADPrincipalGroupMembership -Identity $user.UserName | Where-Object {
$_ -ne $primaryGroup
} | ForEach-Object {
Remove-ADGroupMember $_ -Members $user.username -Confirm:$False -WhatIf
}
}
Since this has the potential to be a very destructive command, I have included a safeguard in the example above. Remove the -WhatIf parameter from Remove-ADGroupMember to actually perform the removal.

I'd propose a slightly different approach - just drop Get-ADPrincipalGroupMembership altogether. For example:
$users = Import-Csv -Path c:\temp\leavers.csv
foreach ($user in $users) {
# Assuming DN is not in the csv...
$distinguishedName = (Get-ADUser -Identity $user.UserName).DistinguishedName
Get-ADGroup -LdapFilter "(member=$distinguishedName)"
# Alternatively, just pipe memberOf property to Get-ADGroup...
(Get-ADUser -Identity $user.UserName -Property MemberOf).MemberOf |
Get-ADGroup
}
That way you don't have to filter out something you insisted on getting (by using above mentioned cmdlet).

Related

Removing users from AD group given e-mail address in a CSV file

I have a CSV file of e-mail addresses. The CSV file has one column with the header name. I want to remove the Active Directory users associated with these addresses from a specific group.
Here's my attempt, but it seems like $user is not getting populated.
$data = import-csv -Path C:\Users\39415\Desktop\remove1.csv
ForEach ($name in $data)
{
$user = Get-ADUser -Filter {mail -eq "$_"} | Select SamAccountName
Remove-ADGroupMember -Identity "group name" -Members $user.SamAccountName -Confirm:$false
}
Please let me know what i'm doing wrong.
The biggest issue I see right away is you are using a named variable in your foreach loop but then trying to reference automatic variable $_
To use the named variable, change to
$data = import-csv -Path C:\Users\39415\Desktop\remove1.csv
ForEach ($name in $data.name)
{
$user = Get-ADUser -Filter "mail -eq '$name'" | Select SamAccountName
Remove-ADGroupMember -Identity "group name" -Members $user.SamAccountName -WhatIf
}
To use the automatic variable, change to Foreach-Object (still can be shortened to foreach but the former is known as the "foreach statement"
$data = import-csv -Path C:\Users\39415\Desktop\remove1.csv
$data.name | foreach {
$user = Get-ADUser -Filter "mail -eq '$_'" | Select SamAccountName
Remove-ADGroupMember -Identity "group name" -Members $user.SamAccountName -WhatIf
}
Also as I've shown you actually need to reference the name property of the $data variable.

Remove all groups withen a specific OU

I'm attempting to make an AD cleanup script that will go through a terminated OU and verify all users are removed from specific OU's. currently if I run it it will remove all users in the terminated OU from all OU's. I might just be blind but is there an easy way to have it only remove groups from selected OU's?
$OUs = "OU=Terminated,OU=####,OU=####,DC=####,DC=####"
$results = foreach ($OU in $OUs) {
get-aduser -SearchBase $OU -filter * -properties MemberOf | foreach-object {
? $_.MemberOf -like "*OU I want removed*" | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false -whatif
}
}
$results | Export-Csv '.\Users groups have been remoed from.csv' -NoTypeInformation
I thought it would work, however all it gives me is:
Where-Object : A positional parameter cannot be found that accepts argument 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection'.
At C:\###\###\###\accounts script.ps1:8 char:13
+ ? $_.MemberOf -like "*Distrobution Lists*" | <#%{$keep -n ...
Given that you have a separate OU for groups, you can iterate over the groups that a terminated user has and see if any of the groups belong to that specific OU. If thats the case, then remove all those groups.
$results = ""
foreach ($ou in $OUs)
{
$users = Get-ADUser -SearchBase $ou -Filter *
foreach ($user in $users)
{
$groups = Get-ADPrincipalGroupMembership -Identity $User | ? {$_.distinguishedName -like "*OU I WANT TO REMOVE FROM*" }
foreach($group in $groups)
{
Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $group -whatif
results += "$user removed from its Groups: $($groups | % { $_.name })\r\n"
}
}
}
results | Out-File -Append C:\temp\new.txt
$groups will have members in this format. You can use distinguishedName as a filter type and use something like "OU=Groups,DC=this,DC=com" instead of "OU=Groups" that might be considered broad.
distinguishedName : CN=GroupName,OU=****,DC=****,DC=****
GroupCategory : Security
GroupScope : Global
name : <Name Of The Group>
objectClass : group
objectGUID : <Object Guid>
SamAccountName : <Name Of The Group>
SID : <SID>
I like to keep the variables so i can use them to log what changes are being performed.
NOTE: I used -whatif to make sure it doesnt do what you intend to for testing reasons. Remove-ADPrincipalGroupMembership also updates user with one group.
Another Way to go about it
foreach ($ou in $OUs)
{
$users = Get-ADUser -SearchBase $ou -Filter *
$groups = Get-ADGroup -Filter * -SearchBase $DecomOUGROUP
foreach($group in $groups) {
Remove-ADGroupMember -Identity $group -Members $users -ErrorAction SilentlyContinue
}
}

Remove list of users from list of groups, BUT users from a different domain (foreign security principals)

I have a list of accounts (SAM account names) and a list of groups all the accounts need to be removed from. My problem is that I have to specify -server DC01 since the users are in a different domain. I can do that for removing 1 user at a time with:
$Groups = Get-Content C:\temp\groups.txt
$user = get-aduser <username> -Server "DC01.domain.com"
foreach ($Group in $Groups) {
Write-Host "Removing $user from $group" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
}
But I have several long lists of users, and there's got to be a way to do this for all of them.
I tried adding the ** entries below, but no dice:
$Groups = Get-Content C:\temp\groups.txt
$user = Get-Content C:\temp\users0.txt **-Server "DC01.domain.com"**
foreach ($Group in $Groups) {
Write-Host "Removing $user from $group" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Members $user **-searchbase = "DC=domain,DC=com"** -Confirm:$false
}
Thanks in advance for any suggestions!
I cannot test this right now, but I believe you can set the -Members parameter to an array of users.
Apparently, the Remove-ADGroupMember does not work if you supply an array of DistinguishedNames when the users are from another domain, so we need to use the full default (Microsoft.ActiveDirectory.Management.ADUser) objects as returned by the Get-ADUser cmdlet.
$DCGroups = (Get-ADDomain your.domainA.com).PDCEmulator # get a PDC emulator in domain A where the groups are
$DCUsers = (Get-ADDomain your.domainB.com).PDCEmulator # get a PDC emulator in domain B where the users are
$Groups = Get-Content 'C:\temp\groups.txt' # the groups are in domainA
# get an array users ADUser Objects from Domain B
$users = Get-Content 'C:\temp\users0.txt' | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Server $DCUsers -ErrorAction SilentlyContinue
if ($user) { $user }
}
# remove these users from the groups in Domain A
foreach ($Group in $Groups) {
Write-Host "Removing $($users.Count) users from $Group" -Foreground Yellow
Remove-ADGroupMember -Identity $Group -Members $users -Confirm:$false -Server $DCGroups
}
Edit
To overcome the exception being thrown when you try to remove a user that is not a member of the group, you need to add some extra code to make sure the -Members parameter of Remove-ADGroupMember contains only ADUser objects that currently are member of this group.
$DCGroups = (Get-ADDomain your.domainA.com).PDCEmulator # get a PDC emulator in domain A where the groups are
$DCUsers = (Get-ADDomain your.domainB.com).PDCEmulator # get a PDC emulator in domain B where the users are
$Groups = Get-Content 'C:\temp\groups.txt' # the groups are in domainA
# get an array users ADUser Objects from Domain B
$users = Get-Content 'C:\temp\users0.txt' | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Server $DCUsers -ErrorAction SilentlyContinue
if ($user) { $user }
}
# remove these users from the groups in Domain A
foreach ($Group in $Groups) {
# get a list of SamAccountNames of users that are currently a member of this group
$members = Get-ADGroupMember -Identity $Group | Where-Object {$_.objectClass -eq 'user'} | Select-Object -ExpandProperty SamAccountName
# create a subset of users that are indeed in the members list
$removeThese = #($users | Where-Object { $members -contains $_.SamAccountName })
if ($removeThese.Count) {
Write-Host "Removing $($removeThese.Count) users from $Group" -Foreground Yellow
Remove-ADGroupMember -Identity $Group -Members $removeThese -Confirm:$false -Server $DCGroups
}
else {
Write-Host "No users need to be removed from group '$Group' " -Foreground Green
}
}

Deleting Users from multiple groups AD Powershell

I have a .csv file with the group names and the SAM of the users I want to delete from the 10 groups.
How does this work? I am a PowerShell beginner.
Save the user list as csv and use something like
$users = import-csv C:\csvpath\users.csv
Foreach ($user in $users){
Remove-adgroupmember -identity "groupname1" -members $user.username -Confirm:$false
Remove-adgroupmember -identity "groupname2" -members $user.username -Confirm:$false
}
You could of course also get the groupnames from another csv to get a cleaner code
$users = import-csv C:\csvpath\users.csv
$groups = import-csv C:\csvpath\groups.csv
Foreach ($user in $users){
Foreach ($group in $groups) {
Remove-adgroupmember -identity $group.name -members $user.username -Confirm:$false
}
}

Powershell Adding users within groups to cross forest groups

This script works without error now, but the problem is that when several groups in the searchbase are found, the script will add all users from all groups to the cross forest target groups.
So for example:
ForestAGroup1 = contains 2 users
ForestAGroup2 = contains 2 users
::runs script::
now...
ForestBGroup1 = contains 4 users
ForestBGroup2 = contains 4 users
The ForestBGroup1/2 needs to contain the same identical users as ForestAGroup1/2.
Here is the script for reference:
$creds = Get-Credential
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com" | export-csv c:\temp\test.csv
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com"
Foreach($G In $Groups)
{
#Display group members and group name
Write-Host $G.Name
Write-Host "-------------"
$G.Members
#Add members to domainB group
$domainGMembers = import-csv C:\temp\test.csv | ForEach-Object -Process {Get-ADGroupMember -Identity $_.CN} | Select-Object samaccountname | export-csv c:\temp\gmembers.csv
$domainDNUser = import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Get-ADUser $_.samaccountname -Server "domainA.com" -properties:Distinguishedname}
import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Add-ADGroupMember -Server "domainB.com" -Identity $G.Name -Members $domainDNUser -Credential $creds -Verbose}
}
What are you doing?
You export to csv, but still try to save it to a variable
You search twice
You add all members from ALL groups in TEST-OU to every group in domainB
You waste time on saving and reading data that you already have in memory
You search for the user-object to get SamAccountName when you already have something ten times better, the DN. Then you use that SamAccountName to find the DN.
Try this (untested):
$creds = Get-Credential
$Groups = Get-ADGroup -Properties Members -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domain,DC=com"
Foreach($G In $Groups)
{
#Display group members and group name
Write-Host $G.Name
Write-Host "-------------"
$G.Members
#Add members to domainB group
$G.Members |
Get-ADUser -Server fairfieldmfg.com |
ForEach-Object { Add-ADGroupMember -Server "domainB.com" -Identity $G.Name -Members $_ -Credential $creds -Verbose }
}
I used a foreach-loop to run the Add-ADGroupMember because it usually fails in the middle of a group of members if it finds on the already is a member, but if we add them one at a time you get around that (or you could do a search and exclude those already in the group).
You may want to add -ErrorAction SilentlyContinue to Add-ADGroupMember to ignore those errors when you know the script works as it should.