作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果数组只有一个 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.Count
是
null
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/
我是一名优秀的程序员,十分优秀!