How to check if PSCustomObject is empty in PowerShell?

To check if the PSCustomObject is empty or not in PowerShell, we need to check the fields of the PSCustomObject. Consider the below example,


$output = [PSCustomObject]@{
   Name = 'John'
   City = 'New York'
   Country = 'US'
   Company = 'Alpha'  
$output1 = [PSCustomObject]@{
   Name = ''
   City = ''
   Country = ''
   Company = ''


PS C:\WINDOWS\system32> $output
Name    City     Country    Company
----    ----     -------    -------
John    New York  US        Alpha
PS C:\WINDOWS\system32> $output1
Name    City     Country    Company
----    ----     -------    -------

In this example, we have Output and Output1 PSCustomObjects and the output1 is the empty one. First of all, we can’t determine by the Count property because no such direct method exists for the Custom Objects. For example,


PS C:\WINDOWS\system32> $output.count
PS C:\WINDOWS\system32> $output1.count

There will be no output because Count is not supported in the PSCustomObject but if we convert it to the string using the ToString() method then we can use the count method. For example,


PS C:\WINDOWS\system32> $output.ToString().Count
PS C:\WINDOWS\system32> $output1.ToString().Count

But it entirely considers PSCustomObject as one so always gives the count 1. But we can determine if the PSCustoObject is empty or not by checking its field. So we will check here any property of the column of the object and if it is null then the PSCustomObject is null.

PS C:\WINDOWS\system32> $output.Country -eq ""
PS C:\WINDOWS\system32> $output1.Country -eq ""

So the Output1 Object is empty. In some cases, you can check multiple properties to confirm if the PSCustomObject is empty.