- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
Example
$output = [PSCustomObject]@{ Name = 'John' City = 'New York' Country = 'US' Company = 'Alpha' } $output1 = [PSCustomObject]@{ Name = '' City = '' Country = '' Company = '' }
Output
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,
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,
Example
PS C:\WINDOWS\system32> $output.ToString().Count 1 PS C:\WINDOWS\system32> $output1.ToString().Count 1
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 "" False PS C:\WINDOWS\system32> $output1.Country -eq "" True
So the Output1 Object is empty. In some cases, you can check multiple properties to confirm if the PSCustomObject is empty.