2017-02-28 52 views
1

在PowerShell的空列表上運行.count時,結果爲空,而不是0。爲了與實際量我已經用一個醜陋的解決方法,我很願意進一步合作,以擺脫:在PowerShell中的空列表上計數

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列表爲空時的結果?

+1

不能重現這一點,但在這種情況下,顯式數組通常會有所幫助,比如'@(Get-ADUser ...)。Count' – TToni

+1

我不能重現這個,我也得到'resultCount'。 –

+0

@TToni/@ Jeff ......也許這是由於另一個PowerShell版本? – pagid

回答

3

問題是,如果您的表達式返回一個項目,您會得到該項目而不是列表。該@()運營商將其轉換爲一個列表,如果它是不是已經是一個列表:

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

在使用計數方法之前,請嘗試測量對象。

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

是否將列表轉換爲數組幫助?

$resultCount = (Get-ADUser -properties memberof -filter { ... } | Select -ExpandProperty Name).Count 
1
$resultCount = ((get-aduser -filter {name -like "*z*"}).Name).count 

這甚至在空數組的情況下返回0。在數組上調用.Name將創建數組名稱。在現代PowerShell中,每個變量即使不是數組,也具有.count屬性,並且可以解決[0]