Forum Discussion

ADumith's avatar
ADumith
Iron Contributor
Apr 19, 2023

Removing user from all groups in an AD

Hello everyone, 

 

I'm trying to use this script to accept input from the user based on what user they want removed from all groups, but I need the script make sure that the user account is not enable prior to remove all the groups.

 

 

$User1 = Read-Host -Prompt 'Enter the username of the employee you wish to change'

Get-ADUser -Identity $User1 -Properties MemberOf | ForEach-Object 
{
  $_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false
}

 

 

Thank you in advance, 

 

  • Andres-Bohren's avatar
    Andres-Bohren
    Steel Contributor

    Hi ADumith 

     

    This Script schould do it

     

    $Username = Read-Host -Prompt 'Enter the username of the employee you wish to change'

    $ADUser = Get-ADUser -Identity $Username -Properties MemberOf
    If ($ADUser -eq $Null)
    {
    #User not found
    Write-Host "User not found" -ForegroundColor Red
    } else {
    #User Found
    If ($ADUser.Enabled -eq $True)
    {
    Write-Host "User is not disabled" -ForegroundColor Yellow
    } else {
    #User is disabled
    [array]$Groups = $AdUser.MemberOf
    Foreach ($Group in $Groups)
    {
    Write-Host "Working on: $Group"
    Remove-ADGroupMember -Identity "$Group" -Members $($ADUser.SamAccountName) -Confirm:$false
    }
    }
    }

     

    Regards Andres

    • ADumith's avatar
      ADumith
      Iron Contributor

      Hello Andres-Bohren 

       

      I was testing the script, but I'm not sure if there is something wrong on my end or this is expected.

       

      Any how, when I enter a wrong user name, I'm getting this message:

      Get-ADUser : Cannot find an object with identity: 'xyzqwe3' under: 'DC=mydom,DC=xft'.
      At line:3 char:11
      + $ADUser = Get-ADUser -Identity $Username -Properties MemberOf
      +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : ObjectNotFound: (xyzqwe3:ADUser) [Get-ADUser], ADIdentityNotFoundException
          + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

       

      Thank you in advance, 

       

      • Andres-Bohren's avatar
        Andres-Bohren
        Steel Contributor
        Change this line
        $ADUser = Get-ADUser -Identity $Username -Properties MemberOf -ErrorAction SilentlyContinue

Resources