0

I am trying to run a Script, which gets all users from a specific OU and the removes all those users from the groups they are apart of. Ive tried multiple things but I just cannot get it right.

My Code currently looks like this:

     $DisabledUser = Get-ADUser -Searchbase "OU=This,OU=Users,OU=Is,DC=A,DC=Test" -Properties * -Filter {Enabled -eq $false}  | Select-Object UserPrincipalName, DistinguishedName, MemberOf
 
 foreach ($user in $DisabledUser) {
  $GroupMemberships = Get-ADUser -Identity $DisabledUser -MemberOf
  foreach ($Groups in $GroupMemberships) {
  Remove-ADGroupMember -Identity $Groupmembership.DistinguishedName -Members $user.ObjectId -WhatIf
   }
 } 

Any Idea if the way im doing it is correct or if this is a complete shot in the dark.

Unfortunately, I only do not get anything. No error code or anything. It just runs and blanks out.

ri2312
  • 9
  • 2
  • [1] Don't ask for `Properties *` if you don't need **all** properties. [2] Inside the loop you already have all that is required in `$user`, so no need to do Get-ADUser again [3] instead of `$user.ObjectId` use `$user` [4] you are iterating with variable `$Groups`, but you use `$Groupmembership.DistinguishedName` instead.. – Theo Mar 03 '23 at 10:53

1 Answers1

0

As commented, there are some flaws in your code:

  • You should not use -Properties * if all you need is just one extra property MemberOf
  • inside the main loop, you again call GetADUser, which is overkill as you already have all information you need in the iterating variable
  • in both loops you are not using the iterating variable, but the whole collection. The syntax is
    foreach ($singleItem in $collectionOfItems) { <# do something with $singleItem here #> }

Try

$OU = 'OU=This,OU=Users,OU=Is,DC=A,DC=Test'

# Get-ADUser by default returns objects with these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, 
# SamAccountName, SID, Surname, UserPrincipalName
# if you need extra properties specify these in parameter -Properties

# instead of -Filter you can also use -LDAPFilter '(userAccountControl:1.2.840.113556.1.4.803:=2)'
$DisabledUsers = Get-ADUser -Searchbase $OU -Properties MemberOf -Filter 'Enabled -eq $false'
foreach ($user in $DisabledUsers) {
    # loop over the user's MemberOf collection of DistinguishedNames
    $user.MemberOf | ForEach-Object {
        $_ | Remove-ADGroupMember -Members $user -WhatIf
    }
} 
Theo
  • 57,719
  • 8
  • 24
  • 41