gpt4 book ai didi

powershell - 使用 pscustomobjects 在 PowerShell 中计算数组的属性

转载 作者:行者123 更新时间:2023-12-03 23:36:34 24 4
gpt4 key购买 nike

如果数组只有一个 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 做 unboxing一个单项数组,所以如果有一个数组,你会得到一个数组,所以这个方法可以绕过默认的 Powershell 行为来处理单项数组。您体验 Count为 1 因为在 Powershell 3.0 Microsoft fixed one-item arrays by adding Count property to every object这样一个对象的索引返回 Count为 1,对于 $null返回零,但 PSCustomObject s 被排除在此之外,因为自然原因声明它们可以包含自己的 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:> (hehe).count

VERBOSE: 1

2

关于powershell - 使用 pscustomobjects 在 PowerShell 中计算数组的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com