Managing the position of function parameters
Table of Contents
I. Introduction
In a PowerShell function, and in the same way as with certain PowerShell cmdlets, you can impose the position of a parameter. In other words, you can impose the order in which parameters must be specified when calling a function, when parameter names are not specified. We'll look at this concept in more detail in this chapter.
II. Syntax
To indicate the position of a parameter, you need to specify a number, knowing that the first position is"0". This declaration must be specified like this:
param([Parameter(Position=0)]$Nom)
If you want this parameter to be mandatory and its position to be"0", here is the syntax for adding these two instructions to the same parameter:
param([Parameter(Mandatory=$true,Position=0)]$Nom)
III. Example
We'll take the example of the "Get-Login" function and associate position 0 with the"First name" parameter and position 1 with the"Last name" parameter. The result is as follows:
function Get-Login {
param([Parameter(Mandatory=$true,Position=1)][ValidatePattern("^[a-z]+$")]$Nom,
[Parameter(Mandatory=$true,Position=0)][ValidatePattern("^[a-z]+$")]$Prenom)
$Identifiant = (($Prenom).Substring(0,1)).ToLower() + "." + ($Nom).ToLower()
return $Identifiant
}
Once you've added this parameter setting, you'll see that it won't make any difference if you specify the parameter name and value. This means that both commands will give the same result:
Get-Login -Prenom "Florian" -Nom "Burnel"
Get-Login -Nom "Burnel" -Prenom "Florian"
The position of the parameter in play if we call the function and indicate values without specifying parameter names. For example:
Get-Login "Florian" "Burnel"
In this way, the function will take the first value and assign it to the"First name" parameter, and the second value and assign it to the"Last name" parameter. Assigning a position number to each parameter clarifies the function's behavior when we call it without specifying the parameter names.
IV. Conclusion
Parameter position management is not essential, as it's best practice to explicitly specify the parameter name followed by its value. Nevertheless, it makes for an even more complete function that can be called more quickly, especially in console mode.