filter CountFilter($StartAt = 0) { Write-Output ($StartAt++) } function CountFunction { [CmdletBinding()] param ( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] $InputObject, [Parameter(Position=0)] $StartAt = 0 ) process { Write-Output ($StartAt++) } } $fiveThings = $dir | select -first 5 # or whatever "Ok" $fiveThings | CountFilter 0 "Ok" $fiveThings | CountFilter "Ok" $fiveThings | CountFunction 0 "BUGBUG ??" $fiveThings | CountFunction
我搜索了Connect,没有发现任何已知的会导致这种差异的错误。有人知道是不是按设计的?
这出现在MVP邮件列表中。对于adv函数,PowerShell似乎在每次接收管道对象时重新绑定(重新计算)默认值。名单上的人认为这是一个错误。这里有一个解决方法:
function CountFunction { [CmdletBinding()] param ( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] $InputObject, [Parameter(Position=0)] $StartAt ) begin { $cnt = if ($StartAt -eq $null) {0} else {$StartAt} } process { Write-Output ($cnt++) } } $fiveThings = dir | select -first 5 # or whatever "Ok" $fiveThings | CountFunction 0 "FIXED" $fiveThings | CountFunction