我发现的是,当我编写以下功能时:
function test {
Write-Host ($input | Measure-Object).Count
Write-Host ($input | Measure-Object).Count
}
带有样品输入:
dir | test
它在控制台上写入:
18
0
我认为这是因为第一个测量对象覆盖$输入的管道。我知道有一个解决方法,我将制作一个新数组并将其传递到:
function test {
$inp = @($input)
Write-Host ($inp | Measure-Object).Count
Write-Host ($inp | Measure-Object).Count
}
但是我不喜欢它,因为我正在引入一个新变量。留下$输入未受影响时,是否有一种将cmdlet管道的方法?
尝试以下:
function test {
Write-Host ($input | Measure-Object).Count
$input.reset()
Write-Host ($input | Measure-Object).Count
}
阅读有关$input
Enumerator
$input
是 ArrayListEnumeratorSimple
:
C:Usersroger> $input.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False True ArrayListEnumeratorSimple System.Object
...这意味着它是一系列项目的枚举者。因此,当您食用其中的项目时,您会使用它们。
我尝试以下内容:
function foo
{
$input | select -first 3 | % { Write-Host -ForegroundColor 'Red' $_ }
$input | % { Write-Host -ForegroundColor 'White' $_ }
}
...表明select -first 3
吃了前3个项目,但似乎吞没了所有这些。
尝试以下内容:
function bar
{
$n = 0
foreach ($x in $input) {
if ( ++$n -eq 3 ) { break }
Write-Host -ForegroundColor 'Red' $x
}
$input | % { Write-Host -ForegroundColor 'White' $_ }
}
dir | bar
...显示差异。
但是,由于$输入是枚举器(严格地是IEnumerator
),因此您可以在其上调用Reset()
来倒带。
请注意,在.net-land中,并非所有枚举者都可以重置。我不确定PowerShell中是否有任何情况,$input
。