【问题标题】:Powershell advanced functions: are optional parameters supposed to get initialized?Powershell高级功能:是否应该初始化可选参数?
【发布时间】:2010-01-22 16:42:10
【问题描述】:
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 并没有发现任何会导致这种差异的已知错误。有人知道这是不是设计的吗?

【问题讨论】:

    标签: function powershell parameters powershell-2.0


    【解决方案1】:

    这出现在 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
    

    【讨论】:

    • 我目前使用的解决方法更简单:[Parameter(Position=0)]$StartIndex=0 .... begin { $Counter = $StartIndex }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多