My goal is to drop all members of a few groups in bulk so that I can pull new information from an external database and then repopulate the groups with the updated info.
PowerShell is specifically throwing an error on at Remove-ADPrincipleGroupMembership, with an error message of:
Object reference not set to an instance of an object.
The identity parameter takes a scalar (single) value not a collection. I would bet in
$group is a collection of groups (array) and not a single item which would cause an error.
the ForEach-Object will take your collection (array) $AD_Groups and process them one at a time.
In the first example it is a single group. In the loop, I’m using two groups for now. Even with your response, I’m struggling to understand why it would behave differently. In my mind, it should process each group one at a time, effectively doing the same thing as it does outside of the loop, it just occurs twice.
In your loop you are using $AD_Groups. Is that assigned the same way as $group? Also, inside the loop $group is NOT the same variable as $group outside of it. The foreach loop assigns it to the current item each iteration.
To troubleshoot, you may want to either debug and step through or put some statements to write out the variable values. i.e.
Write-Host ("The value of groups inside the function is {0}" -f $groups.ToString())
Yep, I’ve been using the debugger in VS Code to walk through it. What it seems like to me is that the object that’s created with Get-ADGroupMember -Identity $Group is not being passed over the pipeline to Remove-ADPrincipalGroupMembership ....
$Group DOES contain one of the string’s from $AD_Groups in each interation of the loop in the debugger, which is why I think it’s actually some weird pipeline behavior that is occurring within the loop.
When you debug does every iteration of the loop give you the error or just some? On an iteration that gives you the error, when in debug mode, run just the
OK. So the only other difference I see is back to collection vs. scalar. Assuming the following:
Global variable $AD_Groups is a collection of groups (array) and
Global variable $group is IDENTICAL to global variable $AD_Groups
With those assumptions outside the loop:
The -memberof parameter is getting an array of groups and inside the loop
-memberof parameter is getting a single group.
I don’t know if that is causing your error but it is a difference between the two (given my assumptions)