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,但未找到任何可能导致此差异的已知错误。任何人都知道它是否符合设计要求?
答案 0 :(得分:2)
这出现在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