Moving an AD User from One Group to Another via PowerShell

This week I had a request that seemed rather simple.  Given a CSV file containing the User Principal Name of the user, determine if the user is a member of a specific Active Directory group, remove it, and add it as a member to another specific Active Directory group.  I am not sure of what the purpose of this is, but it is part of an Office 365 migration and given my own experiences with using groups for things security related and not-so-security related, it could simply be a matter of identifying users or classifying them.  Anyhow, the final solution isn’t very complicated, but it is slightly more than what I would have expected.

The problem stems from what I have grown accustomed in dealing with Exchange Management Shell, I can identify a mailbox by numerous methods: Display Name, email address, alias, SAM Account Name, or User Principal Name.  However, the Get-ADUser command doesn’t offer a direct means to identify the user(s) via User Principal Name:


This fails.

The ultimate solution isn’t all that complicated:

Get-ADUser -Filter {UserPrincipalName -eq ""}


So, here is the workflow:

  1. Validate that the user exists (done)
  2. Determine if the user is a member of the “source” group, if not, exit
  3. If the user is a member of the “source” group, remove it
  4. Add the user as a member of the “target” group

So, this requires the Active Directory module within PowerShell (I have not tested this after writing it here, as I simply reproduced it from memory… definitely test and let me know if there is an issue in the comments):

Import-Module ActiveDirectory

$SourceGroup = "<SourceGrpName>"
$TargetGroup = "<TargetGrpName>"
$Users = Import-Csv "<FilePath>" # Contains a list of users as UserPrincipalName

$Users | ForEach-Object {
	$UPN = $_.UserPrincipalName
	$User = Get-ADUser -Filter {UserPrincipalName -eq "$UPN"}
	If($User.Count -eq 0) {
		Write-Host "Error: user ""$UPN"" does not exist"
	} Else {
		$Group = Get-ADGroup "$SourceGroup" -Properties Member
		If($Group.Count -eq 0) {
			Write-Host "Error: source group ""$SourceGroup"" does not exist"
		} Else {
			If($Group.Member -Contains $User.DistinguishedName) {
				Remove-ADGroupMember $Group -Member $User -Confirm:$False
				Get-ADGroup "$TargetGroup" | Add-ADGroupMember -Member "$User"
			} Else {
				Write-Host "Exiting: user ""$UPN"" is not a member of group ""$SourceGroup""



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s