依靠 PowerShell 中的空列表
Count on empty list in PowerShell
当 运行 在 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
作为结果?
在使用计数方法之前先尝试 Measure-Object。
$resultCount = (Get-ADUser -properties memberof -filter { ... } | Select Name| Measure-Object).count
将列表转换为数组有帮助吗?
$resultCount = (Get-ADUser -properties memberof -filter { ... } | Select -ExpandProperty Name).Count
问题是,如果您的表达式 returns 一个项目,您将得到该项目,而不是一个列表。如果它还不是列表,@()
运算符会将其转换为列表:
$resultCount = (@(Get-ADUser -properties memberof -filter { ... } | Select Name)).count
$resultCount = ((get-aduser -filter {name -like "*z*"}).Name).count
这将 return 即使在空数组的情况下也是 0。在数组上调用 .Name
将创建名称数组。在现代 powershell 中,每个变量即使不是数组也有 .count
属性 并且可以被寻址 [0]
.
当 运行 在 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
作为结果?
在使用计数方法之前先尝试 Measure-Object。
$resultCount = (Get-ADUser -properties memberof -filter { ... } | Select Name| Measure-Object).count
将列表转换为数组有帮助吗?
$resultCount = (Get-ADUser -properties memberof -filter { ... } | Select -ExpandProperty Name).Count
问题是,如果您的表达式 returns 一个项目,您将得到该项目,而不是一个列表。如果它还不是列表,@()
运算符会将其转换为列表:
$resultCount = (@(Get-ADUser -properties memberof -filter { ... } | Select Name)).count
$resultCount = ((get-aduser -filter {name -like "*z*"}).Name).count
这将 return 即使在空数组的情况下也是 0。在数组上调用 .Name
将创建名称数组。在现代 powershell 中,每个变量即使不是数组也有 .count
属性 并且可以被寻址 [0]
.