Remove user from specific AD groups using PowerShell

remove

If you are looking for simple AD group member removal script this article is for you. Today I want to share few examples about getting group membership and removing one specific user from multiple groups. I was using commands form ActiveDirectory module.

Get user group membership

Below you can find several commands which helps to get user direct group mmebership:

#Display DN of groups using adsisearcher
([adsisearcher]"(samaccountname=$env:USERNAME)").FindOne().Properties.memberof

#Display DN of groups
(Get-ADUser pawel.janowicz -Properties memberof).memberof

#Display DN of groups and copy results to clipboard
(Get-ADUser pawel.janowicz -Properties memberof).memberof | clip

#Display name of groups
((Get-ADUser pawel.janowicz -Properties memberof).memberof | Get-ADGroup).name

#Pass output from memberof parameter and get information about this AD Object
((Get-ADUser pawel.janowicz -Properties memberof).memberof | Get-ADObject) | Select Name,ObjectClass | Sort-Object Name 

#Get detailed information about groups and format output
((Get-ADUser pawel.janowicz -Properties memberof).memberof | Get-ADGroup) | Select Name,GroupCategory,GroupScope| Sort-Object Name | Format-Table -AutoSize -Wrap
Remove user group membership

Removing user from specific group is pretty simple. You just have to use Remove-ADGroupMember command. Please remember to test these command in your lab environment:

#Remove user pawel.janowicz from group PSBros
Remove-ADGroupMember -Identity "pawel.janowicz" -Member "PSBros_group"

#Remove two users from group PSBros and don't ask for confirmation
Remove-ADGroupMember -Identity "pawel.janowicz","artur.brodzinski" -Member "PSBros_group" -Confirm:$false

#Remove user with DistinguishedName 'CN=pawel.janowicz,DC=PSBros' from the 'PSBros' group 
Get-ADGroup -Identity "PSBros_group" | Remove-ADGroupMember -member "CN=pawel.janowicz,DC=PSBros"

#Remove all group membership for user pawel.janowicz and ask for confirmation
Get-ADUser -Identity pawe.janowicz -Properties MemberOf | ForEach-Object {
  $_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$True
}

#Get group names from txt file,foreach remove member pawel.janowicz from it and don't ask for confirmation
Get-Content "C:\users\$env:username\desktop\groups.txt" | %{ Remove-ADGroupMember -Identity $_ -Members "pawel.janowicz" -Confirm:$false }
Remove user group membership script

Final script is basically based on this simple foreach loop.

    $User = "pawel.janowicz"
    $Username = (Get-ADUser -Identity $User.trim() -ErrorAction Stop)
    $ADGroups = Get-Content "C:\users\$env:username\desktop\groups.txt" 
    Foreach($Group in $ADGroups){
        $Group = $Group.Trim()
        "Processing $Group"
        $GroupDetails = Get-ADGroup $Group -Properties members -ErrorAction SilentlyContinue | Where-Object {$_.members -eq $Username.DistinguishedName}
        If($GroupDetails){
             Remove-ADGroupMember -Identity $GroupDetails.DistinguishedName -Members $Username.DistinguishedName -Confirm:$false
        }
    }

Below ou can find combination of a simple loop, creating new object and finally adding it to an array.

    $Report = $User = $Username = $ADGroups = $null
    #=========================================================================================================================
    #Array
    $Report = @()

    #=========================================================================================================================
    #User
    Try{
        $User = Read-Host "Please provide username"
        $Username = (Get-ADUser -Identity $User.trim() -ErrorAction Stop)
    }
    Catch{
        $_.Exception.Message
        Read-Host "Press any key to exit..."
        Exit
    }

    #=========================================================================================================================
    #Groups
    $ADGroups  = Get-Content "C:\users\$env:username\desktop\groups.txt" 

    #=========================================================================================================================
    #Checking user groups
    Write-Host "User: $($Username.name)" -ForegroundColor Green
    Foreach($Group in $ADGroups){
        $Group = $Group.Trim()
        $GroupDetails = $Status = $Removed = $Object = $null
        "Processing $Group"
        $GroupDetails = Get-ADGroup $Group -Properties members -ErrorAction SilentlyContinue | Where-Object {$_.members -eq $Username.DistinguishedName}
        If($GroupDetails){
            $Status = "True"
            Try{
                Remove-ADGroupMember -Identity $GroupDetails.DistinguishedName -Members $Username.DistinguishedName -Confirm:$true -ErrorAction Stop
                $Removed = "True"
            }
            Catch{
                $_.Exception.Message
                $Removed = "False"
            }
        }
        Else{
            $Status = "False"
            $Removed = " - "
        }
        $Object = New-Object PSObject -Property ([ordered]@{ 
    
            Username                = $Username.Name
            GroupName               = $Group
            Member                  = $Status
            Removed                 = $Removed
                    
        })
        $Report += $Object
    }
    If($Report){
        Return $Report | Out-GridView -Title "Resutls for $($Username.name)"
    } 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.