Non empty Arrays and properties

Sorry, vague title!

I learnt something new today. Surprised it took me so long to learn it.

One thing I usually do when checking whether the output of some cmdlet that I store in a PowerShell variable is empty or not is cast it into an array and check its count. Like this:

Here I cast the $approverIds variable to an array first to cater to the edge case of it being an array with a single element. Alternatively I could have done:

That is, cast it as an array initially itself.

There is a problem with this method though and that’s the following:

Same code, except that now I am  getting a property (Id). You’d think I’ll still have an empty array if the Get-MgGroupMember cmdlet doesn’t return anything, but that’s not true any more. Because what happens is the array now has an empty object – it looks like an empty object is created even when Get-MgGroupMember returns nothing, because I am asking for the Id property and that results in an object being created. This bit me in the a$$ today.

Interestingly, if I look at the size of the array via $approverIds.Count it’s 0. It’s only if I cast it to an array, and look at the size of that (@($approverIds).Count), do we get a count of 1.

So, to remember: Create the array first, get a count, and then extract any properties.