如何在 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。但是我们可以通过检查其字段来确定 PSCustoObject 是否为空。因此,我们将在这里检查对象的任何属性,如果它为空,则 PSCustomObject 为空。

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

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

更新于:2021年2月8日

3K+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.