views:

477

answers:

2
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

I searched Connect and didn't find any known bugs that would cause this discrepancy. Anyone know if it's by design?

+1  A: 

This came up on the MVP mail list. It seems that with adv functions, PowerShell is rebinding (reevaluating) the default value each time a pipeline object is received. The folks on the list considered this a bug. Here's a workaround:

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
Keith Hill
The workaround I'm currently using is even simpler: [Parameter(Position=0)]$StartIndex=0 .... begin { $Counter = $StartIndex }
Richard Berg
A: 

I am trying to build a cmdlet which is to when system boots up number lock turns on by default. Can you give me some hits? Thank you so much! Cheers Jeff

jeff