Powershell: Remove AD Group Memberships from OU: Difference between revisions
From Rabbi Blog
(Created page with "=Purpose= This script was an extension of Powershell: AD Group Membership from OU and is quite dangerous. It will run through the designated OU and remove any security gr...") |
(No difference)
|
Revision as of 20:22, 23 May 2019
Purpose
This script was an extension of Powershell: AD Group Membership from OU and is quite dangerous. It will run through the designated OU and remove any security groups designated (or you can give it a list to ignore, which is even more dangerous if you the list is empty). Has very basic logging to csv so you could rebuild if you had to.
To Do
- build in a failsafe check ala DO YOU REALLY WANT TO DO THIS?
- build in a check for OUs never to run against (allow a list of OU's to be programmed that you couldn't run this against)
- figure out a variable check for Test vs Nuke vs Confirm (maybe default to Test)
- learn how to read in from a list into an array for a .ignore list (or .nuke list)
Code
##################################################
## Remove Groups from Users found in target $OU ##
##################################################
## To Do
## - Build Output to Log [Done]
## - Add Flag for Test vs Nuke vs Confirm
## - Warning and Confirmation
##################################################
## Test
## - Multiple -ne in If
## - Array of Groups to ignore
##################################################
# Research: powershell pass variable to parameter
# https://stackoverflow.com/questions/46121939/passing-a-powershell-variable-as-a-cmdlet-parameter
##################################################
###################################################
## User Variables
#$OU = "OU=,OU=,OU=,OU=,DC=rabbibob,DC=com"
$OU = "OU=Users,DC=rabbibob,DC=com"
####################################################
## Logging Setup
$Logfile = "AD_RemoveGroups_CleanUp_20190523.log"
Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
}
# Start
$GetOU = Get-ADUser -SearchBase $OU -Filter *
foreach ($user in $GetOU)
{
$UserDN = $user.DistinguishedName
$Name=$user.SamAccountName
Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
#if ($_.name -notin "Domain Users","RandomSecGrp") #EXCLUSION - slightly more dangerous
if ($_.name -in "Domain Users","RandomSecGrp","AnotherRandomSecGrp","YARSG","WeGetIt_AnotherSecGrp")
{
$Group=$_.name
$LogLine = $Name+","+$Group
LogWrite $LogLine
write-host "$Name - $Group"
### RUN WITHOUT CONFIRMATION
remove-adgroupmember -identity $Group -member $UserDN
### RUN WITH CONFIRMATION
#remove-adgroupmember -identity $Group -member $UserDN -Confirm:$False
}
}
}