如何在 PowerShell 中检查 PSCustomObject 是否为空?
powershellmicrosoft technologiessoftware & coding
要在 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。但我们可以通过检查其字段来判断 PSCustoObject 是否为空。因此,我们将检查对象列的任何属性,如果该属性为空,则 PSCustomObject 为空。
PS C:\WINDOWS\system32> $output.Country -eq "" False PS C:\WINDOWS\system32> $output1.Country -eq "" True
因此 Output1 对象为空。在某些情况下,您可以检查多个属性来确认 PSCustomObject 是否为空。

