Changing AD User Group Memberships












-1















I have an AD container of disabled users that I need to remove all their group memberships. Although I know how to remove the memberships on an individual basis by Read-Host the username, I'm not sure how to do it for all users of the specific container.



I was thinking that the best way to do this would be to use a ForEach-Object to look the command through all the users, but I'm not sure how to make this action for the specific container. The last thing I want to do is to remove group memberships for all my active users.










share|improve this question




















  • 1





    Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

    – Ansgar Wiechers
    Jan 3 at 1:16
















-1















I have an AD container of disabled users that I need to remove all their group memberships. Although I know how to remove the memberships on an individual basis by Read-Host the username, I'm not sure how to do it for all users of the specific container.



I was thinking that the best way to do this would be to use a ForEach-Object to look the command through all the users, but I'm not sure how to make this action for the specific container. The last thing I want to do is to remove group memberships for all my active users.










share|improve this question




















  • 1





    Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

    – Ansgar Wiechers
    Jan 3 at 1:16














-1












-1








-1








I have an AD container of disabled users that I need to remove all their group memberships. Although I know how to remove the memberships on an individual basis by Read-Host the username, I'm not sure how to do it for all users of the specific container.



I was thinking that the best way to do this would be to use a ForEach-Object to look the command through all the users, but I'm not sure how to make this action for the specific container. The last thing I want to do is to remove group memberships for all my active users.










share|improve this question
















I have an AD container of disabled users that I need to remove all their group memberships. Although I know how to remove the memberships on an individual basis by Read-Host the username, I'm not sure how to do it for all users of the specific container.



I was thinking that the best way to do this would be to use a ForEach-Object to look the command through all the users, but I'm not sure how to make this action for the specific container. The last thing I want to do is to remove group memberships for all my active users.







powershell active-directory windows-server-2012






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 1:15









Ansgar Wiechers

146k13133191




146k13133191










asked Jan 3 at 0:57









DavidDavid

326




326








  • 1





    Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

    – Ansgar Wiechers
    Jan 3 at 1:16














  • 1





    Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

    – Ansgar Wiechers
    Jan 3 at 1:16








1




1





Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

– Ansgar Wiechers
Jan 3 at 1:16





Please check the Get-ADUser documentation. Pay particular attention to the -SearchBase parameter.

– Ansgar Wiechers
Jan 3 at 1:16












3 Answers
3






active

oldest

votes


















1














If I understand your question correctly this should do it. I put the -confirm on here so you don't accidentally blow away group members you didn't intent to.



$users=Get-ADUser -SearchBase "OU=Test,DC=domain,DC=com" -Filter *
$groups=Get-ADGroup -Filter *


foreach($group in $groups){
$check=Get-ADGroupMember -Identity $group.Name
foreach($user in $users){
if ($check.name -contains $user.name){
Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm
}
}
}





share|improve this answer































    1














    In addition to specifying a SearchBase in my get-aduser filter, I have an LDAP filter that finds only disabled accounts (we programmatically disable accounts, so there is a single userAccountControl value for all disabled accounts) as I've occasionally seen admins (wrongly) stash an active user in our dedicated disabled user OU.



    The filter also limits the results to disabled users that are members of some group to avoid re-processing people on each batch cycle. This allows me to have another safety -- the batch only removes group memberships if a "reasonable" number of newly disabled accounts are found & sends me an e-mail alert if too many users are returned in the search. What is "reasonable" depends on how many people get disabled between batch runs. When we do a big layoff, I've got to go in and manually up the number to clean up a couple hundred accounts ... but it's saved us when striking workers got disabled (they were not meant to be logging in, but no one wanted to wipe all the group memberships).



    Once you've got the disabled users, iterate through their memberOf values to remove the groups.



    $objDisabledUsers=Get-ADUser -SearchBase "OU=DisabledUsers,DC=example,DC=com" -LDAPFilter "(&(userAccountControl=514)(memberOf=*)(objectCategory=person))" -Properties name, sAMAccountName, memberOf

    if($objDisabledUsers.Count -lt 10){
    foreach($objUser in $objDisabledUsers){
    $objGroupMemberships = $objUser.memberOf
    foreach($strGroup in $objGroupMemberships){
    write-host "Removing $objUser from $strGroup"
    Remove-ADGroupMember -Identity $strGroup -Members $objUser.SamAccountName -Confirm:$false
    }
    }
    }





    share|improve this answer































      0














      So I attempted to use your script example, but I'm running into problems getting things to work and I'm not understanding where I'm messing things up or misunderstanding the error. I've researched on the error and tried to make sense of the "-Identity" parameter, but something is eluding me.



      # Variables
      $User1=Get-ADUser -SearchBase 'OU=Employees DISABLED,DC=domain,DC=com' -Filter *
      $groups=Get-ADGroup "Disabled Users"

      foreach($group in $groups){
      $check=Get-ADGroupMember -Identity $group.Name
      foreach($user in $User1){
      if ($check.name -contains $user.name){
      # Disables named users ActiveDirectory Account.
      Disable-ADAccount -Identity $User1

      # Adds AD group "Disabled Users" to named user group membership
      Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
      }
      }
      }


      However, this is the error message I'm getting:




      Disable-ADAccount : Cannot convert 'System.Object' to the type
      'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
      'Identity'. Specified method is not supported. At
      C:Usersdavid.gageDocumentsPowershellScriptsTEST - Disabled User
      Cleanup.ps1:10 char:46
      + Disable-ADAccount -Identity $User1
      + ~~~~~~
      + CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
      + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount







      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54015077%2fchanging-ad-user-group-memberships%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        If I understand your question correctly this should do it. I put the -confirm on here so you don't accidentally blow away group members you didn't intent to.



        $users=Get-ADUser -SearchBase "OU=Test,DC=domain,DC=com" -Filter *
        $groups=Get-ADGroup -Filter *


        foreach($group in $groups){
        $check=Get-ADGroupMember -Identity $group.Name
        foreach($user in $users){
        if ($check.name -contains $user.name){
        Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm
        }
        }
        }





        share|improve this answer




























          1














          If I understand your question correctly this should do it. I put the -confirm on here so you don't accidentally blow away group members you didn't intent to.



          $users=Get-ADUser -SearchBase "OU=Test,DC=domain,DC=com" -Filter *
          $groups=Get-ADGroup -Filter *


          foreach($group in $groups){
          $check=Get-ADGroupMember -Identity $group.Name
          foreach($user in $users){
          if ($check.name -contains $user.name){
          Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm
          }
          }
          }





          share|improve this answer


























            1












            1








            1







            If I understand your question correctly this should do it. I put the -confirm on here so you don't accidentally blow away group members you didn't intent to.



            $users=Get-ADUser -SearchBase "OU=Test,DC=domain,DC=com" -Filter *
            $groups=Get-ADGroup -Filter *


            foreach($group in $groups){
            $check=Get-ADGroupMember -Identity $group.Name
            foreach($user in $users){
            if ($check.name -contains $user.name){
            Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm
            }
            }
            }





            share|improve this answer













            If I understand your question correctly this should do it. I put the -confirm on here so you don't accidentally blow away group members you didn't intent to.



            $users=Get-ADUser -SearchBase "OU=Test,DC=domain,DC=com" -Filter *
            $groups=Get-ADGroup -Filter *


            foreach($group in $groups){
            $check=Get-ADGroupMember -Identity $group.Name
            foreach($user in $users){
            if ($check.name -contains $user.name){
            Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm
            }
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 3 at 2:29









            dnodno

            112




            112

























                1














                In addition to specifying a SearchBase in my get-aduser filter, I have an LDAP filter that finds only disabled accounts (we programmatically disable accounts, so there is a single userAccountControl value for all disabled accounts) as I've occasionally seen admins (wrongly) stash an active user in our dedicated disabled user OU.



                The filter also limits the results to disabled users that are members of some group to avoid re-processing people on each batch cycle. This allows me to have another safety -- the batch only removes group memberships if a "reasonable" number of newly disabled accounts are found & sends me an e-mail alert if too many users are returned in the search. What is "reasonable" depends on how many people get disabled between batch runs. When we do a big layoff, I've got to go in and manually up the number to clean up a couple hundred accounts ... but it's saved us when striking workers got disabled (they were not meant to be logging in, but no one wanted to wipe all the group memberships).



                Once you've got the disabled users, iterate through their memberOf values to remove the groups.



                $objDisabledUsers=Get-ADUser -SearchBase "OU=DisabledUsers,DC=example,DC=com" -LDAPFilter "(&(userAccountControl=514)(memberOf=*)(objectCategory=person))" -Properties name, sAMAccountName, memberOf

                if($objDisabledUsers.Count -lt 10){
                foreach($objUser in $objDisabledUsers){
                $objGroupMemberships = $objUser.memberOf
                foreach($strGroup in $objGroupMemberships){
                write-host "Removing $objUser from $strGroup"
                Remove-ADGroupMember -Identity $strGroup -Members $objUser.SamAccountName -Confirm:$false
                }
                }
                }





                share|improve this answer




























                  1














                  In addition to specifying a SearchBase in my get-aduser filter, I have an LDAP filter that finds only disabled accounts (we programmatically disable accounts, so there is a single userAccountControl value for all disabled accounts) as I've occasionally seen admins (wrongly) stash an active user in our dedicated disabled user OU.



                  The filter also limits the results to disabled users that are members of some group to avoid re-processing people on each batch cycle. This allows me to have another safety -- the batch only removes group memberships if a "reasonable" number of newly disabled accounts are found & sends me an e-mail alert if too many users are returned in the search. What is "reasonable" depends on how many people get disabled between batch runs. When we do a big layoff, I've got to go in and manually up the number to clean up a couple hundred accounts ... but it's saved us when striking workers got disabled (they were not meant to be logging in, but no one wanted to wipe all the group memberships).



                  Once you've got the disabled users, iterate through their memberOf values to remove the groups.



                  $objDisabledUsers=Get-ADUser -SearchBase "OU=DisabledUsers,DC=example,DC=com" -LDAPFilter "(&(userAccountControl=514)(memberOf=*)(objectCategory=person))" -Properties name, sAMAccountName, memberOf

                  if($objDisabledUsers.Count -lt 10){
                  foreach($objUser in $objDisabledUsers){
                  $objGroupMemberships = $objUser.memberOf
                  foreach($strGroup in $objGroupMemberships){
                  write-host "Removing $objUser from $strGroup"
                  Remove-ADGroupMember -Identity $strGroup -Members $objUser.SamAccountName -Confirm:$false
                  }
                  }
                  }





                  share|improve this answer


























                    1












                    1








                    1







                    In addition to specifying a SearchBase in my get-aduser filter, I have an LDAP filter that finds only disabled accounts (we programmatically disable accounts, so there is a single userAccountControl value for all disabled accounts) as I've occasionally seen admins (wrongly) stash an active user in our dedicated disabled user OU.



                    The filter also limits the results to disabled users that are members of some group to avoid re-processing people on each batch cycle. This allows me to have another safety -- the batch only removes group memberships if a "reasonable" number of newly disabled accounts are found & sends me an e-mail alert if too many users are returned in the search. What is "reasonable" depends on how many people get disabled between batch runs. When we do a big layoff, I've got to go in and manually up the number to clean up a couple hundred accounts ... but it's saved us when striking workers got disabled (they were not meant to be logging in, but no one wanted to wipe all the group memberships).



                    Once you've got the disabled users, iterate through their memberOf values to remove the groups.



                    $objDisabledUsers=Get-ADUser -SearchBase "OU=DisabledUsers,DC=example,DC=com" -LDAPFilter "(&(userAccountControl=514)(memberOf=*)(objectCategory=person))" -Properties name, sAMAccountName, memberOf

                    if($objDisabledUsers.Count -lt 10){
                    foreach($objUser in $objDisabledUsers){
                    $objGroupMemberships = $objUser.memberOf
                    foreach($strGroup in $objGroupMemberships){
                    write-host "Removing $objUser from $strGroup"
                    Remove-ADGroupMember -Identity $strGroup -Members $objUser.SamAccountName -Confirm:$false
                    }
                    }
                    }





                    share|improve this answer













                    In addition to specifying a SearchBase in my get-aduser filter, I have an LDAP filter that finds only disabled accounts (we programmatically disable accounts, so there is a single userAccountControl value for all disabled accounts) as I've occasionally seen admins (wrongly) stash an active user in our dedicated disabled user OU.



                    The filter also limits the results to disabled users that are members of some group to avoid re-processing people on each batch cycle. This allows me to have another safety -- the batch only removes group memberships if a "reasonable" number of newly disabled accounts are found & sends me an e-mail alert if too many users are returned in the search. What is "reasonable" depends on how many people get disabled between batch runs. When we do a big layoff, I've got to go in and manually up the number to clean up a couple hundred accounts ... but it's saved us when striking workers got disabled (they were not meant to be logging in, but no one wanted to wipe all the group memberships).



                    Once you've got the disabled users, iterate through their memberOf values to remove the groups.



                    $objDisabledUsers=Get-ADUser -SearchBase "OU=DisabledUsers,DC=example,DC=com" -LDAPFilter "(&(userAccountControl=514)(memberOf=*)(objectCategory=person))" -Properties name, sAMAccountName, memberOf

                    if($objDisabledUsers.Count -lt 10){
                    foreach($objUser in $objDisabledUsers){
                    $objGroupMemberships = $objUser.memberOf
                    foreach($strGroup in $objGroupMemberships){
                    write-host "Removing $objUser from $strGroup"
                    Remove-ADGroupMember -Identity $strGroup -Members $objUser.SamAccountName -Confirm:$false
                    }
                    }
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 3 at 3:58









                    LisaJLisaJ

                    8091514




                    8091514























                        0














                        So I attempted to use your script example, but I'm running into problems getting things to work and I'm not understanding where I'm messing things up or misunderstanding the error. I've researched on the error and tried to make sense of the "-Identity" parameter, but something is eluding me.



                        # Variables
                        $User1=Get-ADUser -SearchBase 'OU=Employees DISABLED,DC=domain,DC=com' -Filter *
                        $groups=Get-ADGroup "Disabled Users"

                        foreach($group in $groups){
                        $check=Get-ADGroupMember -Identity $group.Name
                        foreach($user in $User1){
                        if ($check.name -contains $user.name){
                        # Disables named users ActiveDirectory Account.
                        Disable-ADAccount -Identity $User1

                        # Adds AD group "Disabled Users" to named user group membership
                        Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
                        }
                        }
                        }


                        However, this is the error message I'm getting:




                        Disable-ADAccount : Cannot convert 'System.Object' to the type
                        'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
                        'Identity'. Specified method is not supported. At
                        C:Usersdavid.gageDocumentsPowershellScriptsTEST - Disabled User
                        Cleanup.ps1:10 char:46
                        + Disable-ADAccount -Identity $User1
                        + ~~~~~~
                        + CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
                        + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount







                        share|improve this answer




























                          0














                          So I attempted to use your script example, but I'm running into problems getting things to work and I'm not understanding where I'm messing things up or misunderstanding the error. I've researched on the error and tried to make sense of the "-Identity" parameter, but something is eluding me.



                          # Variables
                          $User1=Get-ADUser -SearchBase 'OU=Employees DISABLED,DC=domain,DC=com' -Filter *
                          $groups=Get-ADGroup "Disabled Users"

                          foreach($group in $groups){
                          $check=Get-ADGroupMember -Identity $group.Name
                          foreach($user in $User1){
                          if ($check.name -contains $user.name){
                          # Disables named users ActiveDirectory Account.
                          Disable-ADAccount -Identity $User1

                          # Adds AD group "Disabled Users" to named user group membership
                          Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
                          }
                          }
                          }


                          However, this is the error message I'm getting:




                          Disable-ADAccount : Cannot convert 'System.Object' to the type
                          'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
                          'Identity'. Specified method is not supported. At
                          C:Usersdavid.gageDocumentsPowershellScriptsTEST - Disabled User
                          Cleanup.ps1:10 char:46
                          + Disable-ADAccount -Identity $User1
                          + ~~~~~~
                          + CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
                          + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount







                          share|improve this answer


























                            0












                            0








                            0







                            So I attempted to use your script example, but I'm running into problems getting things to work and I'm not understanding where I'm messing things up or misunderstanding the error. I've researched on the error and tried to make sense of the "-Identity" parameter, but something is eluding me.



                            # Variables
                            $User1=Get-ADUser -SearchBase 'OU=Employees DISABLED,DC=domain,DC=com' -Filter *
                            $groups=Get-ADGroup "Disabled Users"

                            foreach($group in $groups){
                            $check=Get-ADGroupMember -Identity $group.Name
                            foreach($user in $User1){
                            if ($check.name -contains $user.name){
                            # Disables named users ActiveDirectory Account.
                            Disable-ADAccount -Identity $User1

                            # Adds AD group "Disabled Users" to named user group membership
                            Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
                            }
                            }
                            }


                            However, this is the error message I'm getting:




                            Disable-ADAccount : Cannot convert 'System.Object' to the type
                            'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
                            'Identity'. Specified method is not supported. At
                            C:Usersdavid.gageDocumentsPowershellScriptsTEST - Disabled User
                            Cleanup.ps1:10 char:46
                            + Disable-ADAccount -Identity $User1
                            + ~~~~~~
                            + CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
                            + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount







                            share|improve this answer













                            So I attempted to use your script example, but I'm running into problems getting things to work and I'm not understanding where I'm messing things up or misunderstanding the error. I've researched on the error and tried to make sense of the "-Identity" parameter, but something is eluding me.



                            # Variables
                            $User1=Get-ADUser -SearchBase 'OU=Employees DISABLED,DC=domain,DC=com' -Filter *
                            $groups=Get-ADGroup "Disabled Users"

                            foreach($group in $groups){
                            $check=Get-ADGroupMember -Identity $group.Name
                            foreach($user in $User1){
                            if ($check.name -contains $user.name){
                            # Disables named users ActiveDirectory Account.
                            Disable-ADAccount -Identity $User1

                            # Adds AD group "Disabled Users" to named user group membership
                            Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
                            }
                            }
                            }


                            However, this is the error message I'm getting:




                            Disable-ADAccount : Cannot convert 'System.Object' to the type
                            'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
                            'Identity'. Specified method is not supported. At
                            C:Usersdavid.gageDocumentsPowershellScriptsTEST - Disabled User
                            Cleanup.ps1:10 char:46
                            + Disable-ADAccount -Identity $User1
                            + ~~~~~~
                            + CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
                            + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount








                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 8 at 20:24









                            DavidDavid

                            326




                            326






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54015077%2fchanging-ad-user-group-memberships%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                A Topological Invariant for $pi_3(U(n))$