指望PowerShell中的空列表

指望PowerShell中的空列表,powershell,powershell-4.0,Powershell,Powershell 4.0,在PowerShell中对空列表运行.count时,结果为空,而不是0。为了进一步处理实际数量,我必须使用一种丑陋的解决方法,我很想摆脱这种方法: Import-Module ActiveDirectory $resultCount = (Get-ADUser -properties memberof -filter { ... } | Select Name).count write-host "count1: $resultCount" if ($resultCount -lt 1)

在PowerShell中对空列表运行.count时,结果为空,而不是0。为了进一步处理实际数量,我必须使用一种丑陋的解决方法,我很想摆脱这种方法:

Import-Module ActiveDirectory
$resultCount = (Get-ADUser  -properties memberof  -filter { ... } | Select Name).count

write-host "count1: $resultCount"

if ($resultCount -lt 1) {
  $resultCount=0
}
write-host ""
write-host "count2: $resultCount"
其中输出为:

count1:
count2: 0

当列表为空时,如何摆脱额外的条件并仍将0作为结果?

在使用计数方法之前,请尝试测量对象

$resultCount = (Get-ADUser  -properties memberof  -filter { ... } | Select Name| Measure-Object).count

在使用计数方法之前,请尝试测量对象

$resultCount = (Get-ADUser  -properties memberof  -filter { ... } | Select Name| Measure-Object).count

将列表转换为数组是否有帮助

$resultCount = (Get-ADUser  -properties memberof  -filter { ... } | Select -ExpandProperty Name).Count

将列表转换为数组是否有帮助

$resultCount = (Get-ADUser  -properties memberof  -filter { ... } | Select -ExpandProperty Name).Count

问题是,如果表达式返回一个项,则得到的是该项,而不是列表。如果它还不是列表,@运算符将其转换为列表:

$resultCount = (@(Get-ADUser  -properties memberof  -filter { ... } | Select Name)).count

问题是,如果表达式返回一个项,则得到的是该项,而不是列表。如果它还不是列表,@运算符将其转换为列表:

$resultCount = (@(Get-ADUser  -properties memberof  -filter { ... } | Select Name)).count
即使是空数组,也将返回0。在数组上调用.Name将创建名称数组。在现代powershell中,每个变量(即使不是数组)都具有.count属性,并且可以寻址[0]


即使是空数组,也将返回0。在数组上调用.Name将创建名称数组。在现代powershell中,每个变量(即使不是数组)都有.count属性,并且可以寻址[0]。

无法重新编程,但在这种情况下,显式数组通常会有所帮助,例如@Get ADUser….CountI也无法复制此属性;我也得到了0的结果帐户。@TToni/@Jeff。。。也许这是由于另一个PowerShell版本?无法重新编程,但在这种情况下,显式数组通常会有所帮助,例如@Get ADUser….CountI也无法复制它;我也得到了0的结果帐户。@TToni/@Jeff。。。可能是因为另一个PowerShell版本?