我发现,当我编写以下函数时:
function test {
Write-Host ($input | Measure-Object).Count
Write-Host ($input | Measure-Object).Count
}使用样例输入:
dir | test它在控制台上写道:
18
0我想这是因为测量对象的第一个管道覆盖了$input。我知道有一种解决方法,我可以创建一个新的数组并将其传递给其他人:
function test {
$inp = @($input)
Write-Host ($inp | Measure-Object).Count
Write-Host ($inp | Measure-Object).Count
}然而,我不喜欢它,因为我引入了一个新的变量。有没有一种方法可以在不影响$input的情况下通过管道连接到cmdlet?
发布于 2012-10-30 22:38:07
试试这个:
function test {
Write-Host ($input | Measure-Object).Count
$input.reset()
Write-Host ($input | Measure-Object).Count
}reading about $input enumerator
发布于 2012-10-30 22:38:19
$input是一个ArrayListEnumeratorSimple
C:\Users\roger> $input.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False True ArrayListEnumeratorSimple System.Object...which意味着它是一系列项的枚举器。因此,当您消费其中的项目时,您就会用完它们。
我尝试了以下操作:
function foo
{
$input | select -first 3 | % { Write-Host -ForegroundColor 'Red' $_ }
$input | % { Write-Host -ForegroundColor 'White' $_ }
}...to显示,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...shows区别。
然而,由于$input是一个枚举器(严格地说是一个IEnumerator),您可以在它上面调用Reset()来倒带它。
请注意,在.NET平台中,并非所有枚举器都可以重置。我不确定在PowerShell中是否有类似$input的场景。
https://stackoverflow.com/questions/13141077
复制相似问题