2010-01-22 47 views
1
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 

我搜索連接並沒有發現任何已知的錯誤,會導致這種差異。任何人都知道這是否是設計?Powershell高級功能:應該初始化的可選參數?

回答

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 
+2

我目前使用的解決方法更簡單:[參數(位置= 0)] $ StartIndex = 0 ....開始{$ Counter = $ StartIndex} – 2010-01-22 18:50:05