我似乎无法正常使用此功能。我想传递一个对象,如果对象为空,则返回1,否则计算对象中的项目并增加1。
假设以下功能“New-Test”:
function New-Test
{
[cmdletbinding()]
Param
(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[object[]]$Object
#[object]$object
)
Begin
{
$oData=@()
}
Process
{
"Total objects: $($object.count)"
if($Object.count -gt 0)
{
$oData += [pscustomobject]@{
Name = $_.Name
Value = $_.Value
}
}
Else
{
Write-Verbose "No existing object to increment. Assuming first entry."
$oData = [pscustomobject]@{Value = 0}
}
}
End
{
$LatestName = ($oData | Sort-Object -Descending -Property Value | Select -First 1).value
[int]$intNum = [convert]::ToInt32($LatestName, 10)
$NextNumber = "{0:00}" -f ($intNum+1)
$NextNumber
}
}
以下测试哈希表:
#Create test hashtable:
$a = 00..08
$obj = @()
$a | foreach-object{
$obj +=[pscustomobject]@{
Name = "TestSting" + "{0:00}" -f $_
Value = "{0:00}" -f $_
}
}
根据上面的函数,如果我传递$ Obj,我得到:
$obj | New-Test -Verbose
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
Total objects: 1
09
这是预期的。但是,如果我通过$ Obj2:
#Create empty hash
$obj2 = $null
$obj2 = @{}
$obj2 | New-Test -Verbose
我明白了:
Total objects: 1
Exception calling "ToInt32" with "2" argument(s): "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: startIndex"
At line:33 char:9
+ [int]$intNum = [convert]::ToInt32($LatestName, 10)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
01
我不明白为什么$ object.count为1,当哈希表中没有任何内容时。
如果我将参数,$ object的类型从[object []]更改为[object],则空哈希表测试结果为:
$obj2 | New-Test -Verbose
Total objects: 0
VERBOSE: No existing object to increment. Assuming first entry.
01
这是我所期望的,但是,如果我运行第一个测试,它会导致:
$obj | New-Test -Verbose
Total objects:
VERBOSE: No existing object to increment. Assuming first entry.
Total objects:
VERBOSE: No existing object to increment. Assuming first entry.
这次$对象中没有任何内容。
我确信这很简单,但我无法理解这一点。任何帮助表示赞赏。
P.S。 PowerShell 5.1
答案 0 :(得分:2)
$obj2
是哈希表,而不是数组。默认情况下不会枚举哈希表,因此哈希表本身就是一个对象。如果您想使用管道循环哈希表,则需要使用$obj2.GetEnumerator()
。
@{"hello"="world";"foo"="bar"} | Measure-Object | Select-Object Count
Count
-----
1
@{"hello"="world";"foo"="bar"}.GetEnumerator() | Measure-Object | Select-Object Count
Count
-----
2