Forum Discussion
Removing user from all groups in an AD
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
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-BohrenApr 20, 2023Iron ContributorChange this line
$ADUser = Get-ADUser -Identity $Username -Properties MemberOf -ErrorAction SilentlyContinue