Default value of parameter is not used in function

后端 未结 4 1189
孤城傲影
孤城傲影 2021-01-01 07:46

I have a very basic PowerShell script:

Param(
    [string]$MyWord
)

function myfunc([string] $MyWord) {
    Write-Host \"$MyWord\"
}
myfunc @PSBoundParamete         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 08:34

    A parameter is bound only if you actually pass it a value, meaning that a parameter's default value does not show up in $PSBoundParameters. If you want to pass script parameters into a function, you must replicate the script parameter set in the function parameter set:

    Param(
        [string]$MyWord = 'hi'
    )
    
    function myfunc([string]$MyWord = 'hi') {
        Write-Host "$MyWord" 
    }
    
    myfunc @PSBoundParameters

    Maintaining something like this is easier if you define both parameter sets the same way, though, so I'd put the function parameter definition in a Param() block as well:

    Param(
        [string]$MyWord = 'hi'
    )
    
    function myfunc {
        Param(
            [string]$MyWord = 'hi'
        )
    
        Write-Host "$MyWord" 
    }

提交回复
热议问题