Tech

PowerShell disable user account and remove group permissions

Hi,

I need a working script to disable a user account and remove all group memberships except for few groups for the users. I am able to disable the user account, but I straguling to choose the correct syntax or appropriate using “Get-” cmdlet to remove the groups permissions.

This is the script what I am using to remove every groups except for the few I specify.

$DomainUsers = "Domain Users"
$O365 = Get-ADGroup -Filter {Name -like "demogroup*"}
$Groups = Get-ADPrincipalGroupMembership -Identity $user

foreach ($group in $groups)
{
	If($group -ne $DomainUsers -and $O365)
		{
			Remove-ADPrincipalGroupMembership -Identity $user 
		}
}

I’m using the variables below to specify which groups need to stay for the accounts. I’m not sure if I should be using Get-ADPrincipalGroupMembership or Get-ADGroup and if I’m missing any other code to get it working correctly.