Accepting an optional parameter only as named, not positional Accepting an optional parameter only as named, not positional powershell powershell

Accepting an optional parameter only as named, not positional


By default, all function parameters are positional. Windows PowerShell assigns position numbers to parameters in the order in which the parameters are declared in the function. To disable this feature, set the value of the PositionalBinding argument of the CmdletBinding attribute to $False.

have a look at How to disable positional parameter binding in PowerShell

function Test-PositionalBinding{    [CmdletBinding(PositionalBinding=$false)]    param(       $param1,$param2    )    Write-Host param1 is: $param1    Write-Host param2 is: $param2}


The main answer still works in version 5 (according to comments, it may have been broken for a while in version 2).

There is another option: add Position to the ValueFromRemainingArgs parameter.

Sample CommandWrapper.ps1:

param(    $namedOptional = "default",    [Parameter(ValueFromRemainingArguments = $true, Position=1)]    $cmdArgs)write-host "namedOptional: $namedOptional"& cmd /c echo cmdArgs: @cmdArgs

Sample output:

>commandwrapper hello worldnamedOptional: defaultcmdArgs: hello world

This appears to follow from PowerShell assigning parameter positions from the first parameter with a Position designated.