Reputation: 961
I have a simple function which has two parameters. I didn't mention them as positional but still, when I check the help for that function it is automatically assigning them a position. How can I force them to be named parameter only (don't accept value by position)?
Function Test-Params
{
Param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
$Param1,
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
$Param2
)
Write-Host "$Param1 $Param2"
}
When I check the help for this function or try to run the function by providing parameter positional values it works (but it shouldn't work):
Test-Params test1 test2
test1 test2
Help output:
help Test-Params -Full
NAME
Test-Params
SYNTAX
Test-Params [-Param1] <Object> [[-Param2] <Object>] [<CommonParameters>]
PARAMETERS
-Param1 <Object>
Required? true
Position? 0
Accept pipeline input? true (ByValue, ByPropertyName)
Parameter set name (All)
Aliases None
Dynamic? false
-Param2 <Object>
Required? false
Position? 1
Accept pipeline input? true (ByValue, ByPropertyName)
Parameter set name (All)
Aliases None
Dynamic? false
Upvotes: 5
Views: 925
Reputation: 58991
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.
So your function looks like this:
Function Test-Params
{
[CmdletBinding(PositionalBinding=$false)]
Param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
$Param1,
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
$Param2
)
Write-Host "$Param1 $Param2"
}
Upvotes: 5