Position and positional binding

Position defaults to -2147483648, the smallest possible value for Int32 (see [Int32]::MinValue). Unless an explicit permission is set, parameters may be bound in the order they are written in the parameter block. Setting the PositionalBinding property of CmdletBinding to false can be used to disable this behavior.

Automatic positional binding is shown in the following example:

function Test-Position {
[CmdletBinding()]
param (
[Parameter()]
$Parameter1,

[Parameter()]
$Parameter2
)

'{0}-{1}' -f $Parameter1, $Parameter2
}

When called, the command shows that Parameter1 and Parameter2 have been filled with the values supplied using position only:

PS> Test-Position 1 2
1-2

Automatic positional binding is available by default; the Parameter attribute is not required. An explicit definition of position allows greater control and effectively disables automatic positional binding:

function Test-Position {
param (
[Parameter(Position = 1)]
$Parameter1,

$Parameter2
)
}

Exploring command metadata shows the positional binding is still enabled, but as this is an ordered operation, the default position no longer has meaning. The command metadata is shown as follows, showing that positional binding is still enabled:

PS> [System.Management.Automation.CommandMetadata](Get-Command Test-Position)

Name : Test-Position

CommandType :
DefaultParameterSetName :
SupportsShouldProcess : False
SupportsPaging : False
PositionalBinding : True
SupportsTransactions : False
HelpUri :
RemotingCapability : PowerShell
ConfirmImpact : Medium
Parameters : {[Parameter1, System.Management.Automation.ParameterMetadata], [Parameter2,
System.Management.Automation.ParameterMetadata]}

Attempting to pass a value for Parameter2 by position will raise an error:

PS> Test-Position 1 2
Test-Position : A positional parameter cannot be found that accepts argument '2'.

At line:1 char:1
+ test-position 1 2
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-Position], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Test-Position

PowerShell orders parameters based on the position value. The value must be greater than -2147483648. It is possible, but not advisable, to set Position to a negative value. The accepted practice has numbering starting at either 0 or 1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.126.74