2015-07-20 32 views
3

如果数组只有一个CustomObjects并且Count属性为null。 为什么?使用pscustomobjects统计PowerShell中的数组的属性

如果仅使用字符串,则Count属性为1。

function MyFunction 
{ 
    $Objects = @() 
    $Objects += [pscustomobject]@{Label = "Hallo"} 
    # $Objects += [pscustomobject]@{Label = "World"} 

    $Objects 
} 

$objs = MyFunction 
Write-Host "Count: $($objs.Count)" 

输出:"Count: "因为$objs.Countnull

function MyFunction 
{ 
    $Objects = @() 
    $Objects += [pscustomobject]@{Label = "Hallo"} 
    $Objects += [pscustomobject]@{Label = "World"} 

    $Objects 
} 

$objs = MyFunction 
Write-Host "Count: $($objs.Count)" 

输出:"Count: 2"

行为是不同的,如果我添加字符串

function MyFunction 
{ 
    $Objects = @() 
    $Objects += "Hallo" 
    # $Objects += [pscustomobject]@{Label = "World"} 

    $Objects 
} 

$objs = MyFunction 
Write-Host "Count: $($objs.Count)" 

输出:"Count: 1"

回答

3

即使嵌套数组由一个对象构成,也可以强制函数返回一个数组。

function MyFunction 
{ 
    $Objects = @() 
    $Objects += [pscustomobject]@{Label = "Hallo"} 
    # $Objects += [pscustomobject]@{Label = "World"} 
    return ,$Objects 
} 

即逗号使得显式转换到即使供给$Objects已经是多于一个的对象的阵列的阵列。这迫使一个元素构造一个数组。在外面,Powershell对单项数组做了unboxing,所以如果有数组的话你会得到一个数组,所以这个方法围绕着默认的Powershell行为来处理单项数组。您遇到Count是1,因为PowerShell中的3.0 Microsoft fixed one-item arrays by adding Count property to every object这样一个对象,它的索引返回Count为1,并为$null返回零,但作为一个自然理性宣称他们可以包含自己的Count性能PSCustomObject s是这个排除在外,因此没有默认Count属性包含在自定义对象中。这就是为什么如果只有一个对象,你不会得到Count

,行为上可以看到下面的例子:

function hehe { 
    [email protected]() 
    $a+=2 
    $a+=4 
    $b=,$a 
    write-verbose $b.count # if a variable is assigned ",$a", the value is always 1 
    return ,$a 
} 

输出:

PS K:>(合).Count之间

VERBOSE:1