簡體   English   中英

使用pscustomobjects在PowerShell中計算數組的屬性

[英]Count property of array in PowerShell with pscustomobjects

如果數組只有一個CustomObjects,則Count屬性為null。 為什么?

如果僅使用字符串,則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"

即使嵌套數組由一個對象構成,也可以強制該函數返回一個數組。

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

即使提供的$Objects已經是一個包含多個對象的數組,該逗號也會顯式轉換為數組。 這會強制構造具有一個元素的數組。 在外部,Powershell會對單項數組進行拆箱 ,因此如果有一個數組,您將獲得一個數組,因此該方法適用於使用單項數組的默認Powershell行為。 您體驗Count為1,因為在Powershell 3.0中Microsoft通過向每個對象添加Count屬性來修復單項數組,以便一個對象的索引將Count返回為1,並且返回$null零,但PSCustomObject被排除在此之外一個自然的原因聲明它們可以包含自己的Count屬性,因此自定義對象不包含默認的Count屬性。 這就是為什么如果只有一個對象你就不會得到Count

行為,可以在以下示例中看到:

function hehe {
    $a=@()
    $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

2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM