Forum Discussion

DamienFR68's avatar
DamienFR68
Copper Contributor
Oct 19, 2023
Solved

Removing users from an AD group

Hello, I am using the following script to remove a batch of users from an AD group: $x=Get-Content "C:\Users\damien.hartmann\Documents\Comptes.txt" for ($i=0; $i -lt $x.Count; $i++) { Remove-ADGro...
  • LainRobertson's avatar
    LainRobertson
    Oct 20, 2023

    DamienFR68 

     

    Yes and no.

     

    In principle, it could be made to work that way but there's two points I'd make:

     

    1. To get that specific type conversion error from your original post, there's something wrong with your input file, since the entire file is considered to be one single string;
    2. Even if the input file were correctly interpreted as a string array, using a "for" loop is very inefficient and won't scale well.

     

    Strictly-speaking, the "for" loop is entirely unnecessary if the input file contains any of the four string references (the most likely string formats to be chosen being either sAMAccountName or distinguishedName).

     

    If the issue with the input file can be fixed, then the simplest and most efficient way to remove the members contained within the input file would be:

     

    Example

    Remove-ADGroupMember -Identity "Office365_LicenceE1_Base" -Members (Get-Content -Path "C:\Users\damien.hartmann\Documents\Comptes.txt") -Confirm:$false;

     

    Imagine your input file had 1,000 users in it at one user per line. Using a "for" loop approach would result in 1,000 separate calls to Active Directory for the setting of the group's "member" attribute.

     

    Using the example above, a single call is made to Active Directory when setting the group's "member" attribute. That's a considerable difference and why there's a tremendous impact on Active Directory when using a loop.

     

    Cheers,

    Lain

Resources