If I understand correctly, you want to remove a specific user from all groups they are a member of. You would like to provide the username either through a CSV file or by manually entering it when running the script. Here's a PowerShell script that allows you to accomplish this:
# Prompt for the username if not using a CSV fileif (-not $csvFilePath) { $username = Read-Host "Enter the username"} else { # Read the username from the CSV file $csvData = Import-Csv -Path $csvFilePath $username = $csvData.Username}# Get the groups the user is a member of$userGroups = Get-ADUser -Identity $username -Properties MemberOf | Select-Object -ExpandProperty MemberOf# Remove the user from each groupforeach ($group in $userGroups) { Remove-ADGroupMember -Identity $group -Members $username -Confirm:$false}Write-Host "User '$username' has been removed from all groups."
This script uses the Active Directory module (requires the RSAT tools) to manage group membership. If you haven't already, you'll need to install the Active Directory module for PowerShell.
To use the script:
Save the script as a .ps1
file (e.g., RemoveUserFromGroups.ps1
).
- If you have a CSV file containing the username(s), ensure the file has a header named "Username" and specify the file path in the
$csvFilePath
variable at the beginning of the script. For example:
$csvFilePath = "C:\Path\To\Users.csv"
If you don't have a CSV file and want to manually enter the username when running the script, leave the $csvFilePath
variable empty.
Open a PowerShell session with administrative privileges.
Navigate to the directory where you saved the script.
- Run the script:
.\RemoveUserFromGroups.ps1
The script will prompt for the username if a CSV file is not used. It will then retrieve the groups the user is a member of and remove the user from each group. Finally, it will display a message indicating that the user has been removed from all groups.