none
PowerShell: Import-CSV - Remove Users from ADGroups RRS feed

  • Question

  • Hi All,

    I am trying to come up with a process to remove a set of disabled users from all their group memberships in AD using a CSV

    I have exported a list of users to a CSV with their SamAccountName and GroupName

    The fields are:

    SamAccountName,Name

    Import-Csv C:\Temp\SAMPLE.csv |
    ForEach-Object {
    get-aduser -filter "SamaccountName -eq '$($_.SamaccountName)'" | Remove-ADGroupMember
        }

    I would like if possible to come up with a way to loop through the CSV and remove the groups but also to reverse this should I need to roll back the change in bulk.

    Any thought's how I might achieve this?

    Thanks

    • Moved by Bill_Stewart Wednesday, September 4, 2019 7:43 PM This is not "fix/debug/rewrite script for me" forum
    Monday, March 25, 2019 2:40 PM

All replies

  • Get the group in the loop and remove the user.  You are doing this backwards.

    Remove-AdGroupMember $_.Name -Member $_.SamAccountName

    To reverse just change "Remove" to "Add".

    Group name must be the full DistinguishedName of the group.  You cannot find a group by name since "Name" is not unique and not an "Identity".


    \_(ツ)_/

    Monday, March 25, 2019 3:04 PM
  • Hope this helps...

    $MyUser="ScottsLogon"
    
    $MyGroups=Get-ADUser $MyUser –Properties MemberOf | Select-Object MemberOf).MemberOf
    
    Foreach($Group in $MyGroups){
    
    	Remove-ADGroupMember -Identity $Group -Member $MyUser
    
    }

    Friday, March 29, 2019 6:37 PM