This script resets the group memberships of a user to only the specified default groups. It’s useful for re-provisioning accounts or handling changes in roles.
# Define the username and default groups
$username = "targetUser"
$defaultGroups = @("Domain Users", "Standard Group") # Replace with desired groups
# Get current groups for the user
$currentGroups = Get-ADUser -Identity $username -Properties MemberOf | Select-Object -ExpandProperty MemberOf
# Remove the user from all current groups
foreach ($group in $currentGroups) {
Remove-ADGroupMember -Identity $group -Members $username -Confirm:$false
}
# Add the user to the default groups
foreach ($group in $defaultGroups) {
Add-ADGroupMember -Identity $group -Members $username
}
Write-Output "Reset group memberships for $username"
• Explanation: This script first removes the user from all current groups and then reassigns them only to the specified default groups.