如何在PowerShell中检查PSCustomObject是否为空?

要在PowerShell中检查PSCustomObject是否为空,我们需要检查PSCustomObject的字段。考虑下面的示例,

示例

$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
----    ----     -------    -------

在此示例中,我们具有Output和Output1 PSCustomObjects,而output1为空。首先,我们无法通过Count属性来确定,因为自定义对象不存在这种直接方法。例如,

示例

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

由于PSCustomObject不支持Count,因此不会有输出,但是如果使用ToString()方法将其转换为字符串,则可以使用count方法。例如,

示例

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

但是它完全将PSCustomObject视为1,因此始终给出计数1。但是我们可以通过检查其字段来确定PSCustoObject是否为空。因此,我们将在此处检查对象列的任何属性,如果该属性为null,则PSCustomObject为null。

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

因此,Output1对象为空。在某些情况下,您可以检查多个属性以确认PSCustomObject是否为空。