Function Powershell高级功能:可选参数是否应该初始化?

Function Powershell高级功能:可选参数是否应该初始化?,function,powershell,parameters,powershell-2.0,Function,Powershell,Parameters,Powershell 2.0,我搜索了Connect,没有发现任何导致这种差异的已知错误。有人知道这是不是出于设计吗?这出现在MVP邮件列表上。似乎使用adv函数,PowerShell在每次接收管道对象时都会重新绑定(重新评估)默认值。名单上的人认为这是一个错误。这里有一个解决方法: filter CountFilter($StartAt = 0) { Write-Output ($StartAt++) } function CountFunction { [CmdletBinding()]

我搜索了Connect,没有发现任何导致这种差异的已知错误。有人知道这是不是出于设计吗?

这出现在MVP邮件列表上。似乎使用adv函数,PowerShell在每次接收管道对象时都会重新绑定(重新评估)默认值。名单上的人认为这是一个错误。这里有一个解决方法:

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

我目前使用的解决方法更简单:[Parameter(Position=0)]$StartIndex=0。。。。开始{$Counter=$StartIndex}
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