Search code examples
powershellactive-directoryadgroup

Powershell - Remove-ADGroupMember


I'm trying to remove the groups from users in other domain.

Example: Me as admin wants to disable an user and remove his groups in other domain.

The problem is I don't know how to use Remove-ADGroupMember -Server in Foreach loop, if I don't use Foreach I can use the -Server option.

Error of Remove-ADGroupmember:
Error of Remove-ADGroupmember

How can I get -Server property within Foreach?

$groups = (Get-Aduser -server ServerY -Identity manusys -Properties MemberOf).memberof

Foreach ($group in $groups) {
    Remove-ADGroupMember -identity $group -Members manusys -Confirm:$false -ErrorAction:SilentlyContinue
}

The user account Manusys has these groups:

CN=NO_CamerasAlertMGR,OU=Ordinary Distribution Lists,OU=Distribution Lists,DC=test,DC=com
CN=NO_CamerasAlertCM,OU=Ordinary Distribution Lists,OU=Distribution Lists,DC=test,DC=com
CN=NO_CamerasReport,OU=Ordinary Distribution Lists,OU=Distribution Lists,DC=test,DC=com
CN=NO_CamerasReport_CM,OU=Ordinary Distribution Lists,OU=Distribution Lists,DC=test,DC=com
CN=NO_CamerasReport_MGR,OU=Ordinary Distribution Lists,OU=Distribution Lists,DC=test,DC=com

Solution

  • The Server param is available to use with Remove-ADGroupMember, using it within foreach doesn't change this.

    Don't just rely on the ISE auto-prompts, referring to the documentation (remove-adgroupmember) will always show you what parameters are available.

    The problem you are actually seeing, is that the ISE no longer prompts/shows the commands parameters once you've used one of the Common Parameters (Confirm & ErrorAction in your code, but there are others)...

    You can see this with the command by itself - it will continue to prompt for params:

    Remove-ADGroupMember -identity $group -Members manusys
    

    But add a CommonParam, and it will not provide its own params anymore:

    Remove-ADGroupMember -identity $group -Members manusys -Confirm:$false
    

    So to fix your original issue, add the Server param to Remove-ADGroupMember:

    $groups = (Get-Aduser -server ServerY -Identity manusys -Properties MemberOf).memberof
    
    Foreach ($group in $groups) {
        Remove-ADGroupMember -server ServerY -identity $group -Members manusys -Confirm:$false -ErrorAction:SilentlyContinue
    }