I have written a script to disable and move users listed in a text file, and as part of this script, I would like to remove them from groups that grant them licenses to certain software.
My script removes the users, but gets stuck in a loop telling me that the group has been removed, and I can't figure out why.
I'm not sure what I'm missing here, help?!?
Thank you!
This is the block that's looping:
foreach ($group in $groups){ #Write-Host $group foreach ($user in Get-ADGroupMember -Identity $group){ If ((Get-ADUser $user.SamAccountName -Properties MemberOf).MemberOf -Contains $group){ Write-Host "$term is a member of $group" Remove-ADGroupMember -Identity $group -Member $user -Confirm:$false Write-Host "$term membership of $group removed." } else{ Write-Host "$term is not a member of any groups" } }
}
This is the whole script if needed (sanitized):
#Import the Active Directory Module for Powershell import-module activedirectory #Get List of Terms $terms = Get-Content "Terms.txt" #Your name $admin = Read-Host -Prompt "Please enter your name " #foreach loop foreach($term in $terms){ $user = Get-ADUser -Filter {displayName -like $term} -Properties CanonicalName #Get location of User $split = $user.DistinguishedName.Split(',') $path = "$($split[-4])" $location = $path $ou = 'OU=Disabled,OU=People,' $dn = ',DC=some,DC=domain,DC=tld' $base = $ou + $location + $dn # disable user Disable-ADAccount -identity $user #Add Description $day = Get-Date -Format g Set-ADUser $user -Description "Disabled by $admin $day" Write-Host "$term Disabled by $admin on $day" #Groups to remove user from on termination $groups = @('CN=Group,OU=SomeOU,OU=Groups,OU=OU2,DC=some,DC=domain,DC=tld', 'CN=Group,OU=SomeOU,OU=Groups,OU=OU2,DC=some,DC=domain,DC=tld', 'sec_software_license_group1', 'sec_software_license_group2', 'sec_software_license_group3') foreach ($group in $groups){ #Write-Host $group foreach ($user in Get-ADGroupMember -Identity $group){ If ((Get-ADUser $user.SamAccountName -Properties MemberOf).MemberOf -Contains $group){ Write-Host "$term is a member of $group" Remove-ADGroupMember -Identity $group -Member $user -Confirm:$false Write-Host "$term membership of $group removed." } else{ Write-Host "$term is not a member of any groups" } } } Write-Host 'Disabling and moving '$term # move user move-adobject -Identity $user -targetpath $base write-host $term' is moved to Disabled' }