I’m new to Powershell, and am building a script to pull various information related to group membership.
Everything works as expected, except for when I am trying to pull a count of domain groups that are direct members of a domain group. It works fine when I have more than 1 domain group that is a direct member i.e. returns 2, 3, 4 etc., but if there is only 1 domain group that is a direct member then $DirectGroupsCount is always blank. $groups is pulling back the domain group that is a direct member and displaying in the console. Any advice?
hi @tbrain1978 and welcome to the forum.
First things first if you wouldn’t mind editing your post and formatting your code as “Preformatted text” that would make it a lot easier for people to help. Guide to Posting Code
This isn’t an answer to your question but a bit of constructive criticism. You’re declaring an empty array and then using the += operation to add objects to that array. It would be less work, and faster, to capture the output of the operation with your array definition like this:
$Groups = Get-AdGroupMember <something>
Get-AdGroupMember specifically returns the members of a given group, then it looks like we’re piping that to Where-Object to filter the output to only include groups that are a member of that provided group. Those go in to our $Groups variable.
Later when you’re defining $DirectGroupsCount there shouldn’t be any need to pipe it to Where-Object again since $Groups should only contain group objectclass objects anyway.
Unfortunately, if there’s only one group object as a member of a group your $Groups variable wouldn’t be an array with a ‘count’ property unless you did it like you have in your code. How I would handle this is this way:
the [Array] syntax is strongly typing the variable $Groups to make sure it’s always an array, even if it only contains one thing. That way the count property will exist.
HI Olaf Thanks for your help with this, and yes, ultimately I’ll need to be querying all of the groups on the domain. I’m going to try and feed this into my script and run a few tests to sanity check that the output is as expected. Thanks so much for your help with this