Counting the objects returned by a PowerShell command

Today I going to write about a little trick I'm using when I want to check the number of objects a PowerShell command returned.

If you execute a PowerShell command that returns some kind of objects, you either get a single object or an array of objects. The array object has a property called "Count" that will return the number of items in the array but what if the command returns a single object? Depending on the implementation of the command that returns the objects,  There is no count property on a single object -and if there is, it's probably irrelevant and will result in a bug.

Using the logic below you can check if the variable "copies" is an array and if not, create an array with the object in the variable.

if($copies -isnot [System.Array]){$copies = @($copies)}

You can also create an array when assigning the result to the variable like:

$copies = @(Get-ChildItem)

The newer versions of PowerShell will allow you to use the Count property on a single object even if it's not available and get the correct result.

Let's see an example from my Exchange server:


Now, first we save the active mailbox database copies to the variable named "copies" but since there's only one object that is returned there is no count for that variable. If assign a table with the result on the "copies" variable, the result is the correct one, that is "1".

Popular posts from this blog

Domain Controller Machine Password Reset

Configuring a Certificate on Exchange Receive Connector

Running Multiple NGINX Ingress Controllers in AKS