Best Practice: It is recommended to use named parameter in your scripts and avoid positional and partial (=truncated, shortened, abbreviated) parameter names in your scripts.
Explanation:
Note: The same logic also could be applied to attribute parameters (line 5)
1 2 3 4 5 6 7 8 |
function Get-Something { Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [string[]]$Path ) } |
===
Additional Information
When using positional parameters, the syntax can be more difficult to read especially with there are many parameters.
By using named parameter, the code is more clear and consistent.
Moreover, with future versions of PowerShell there is no guarantee that these parameters keep the same position (although it should be backwards compatible).
Positional parameters are created that way:
1 2 3 4 5 6 7 8 9 10 11 |
function Get-Something { Param ( [Parameter(Position=0)] # Positional parameter [string[]]$Path, [Parameter(Position=1)] # Positional parameter [string]$Destination ) } |
You will receive an error if the paramete is too ambiguous, in this case it could be -Pa(th) or -Pa(ssThru).
Note: You can also create an alias for a parameter.
Main benefits of parameter aliases:
- Backwards compatibility (if you rename a parameter ‘NewParameter’, you can add a parameter alias to the old name ‘OldParameter’)
- Multiple possible names (you can have multiple names for a same parameter : CN, ComputerName, …)
- Shortcut to the parameter (you can type -CN instead of -ComputerName)
1 2 3 4 5 6 7 8 9 10 11 |
function Get-Something { Param ( [Parameter(Mandatory)] [Alias("FilePath")] [string[]]$Path ) Get-Content -Path $Path } |
Note: If you want to see the correct way to write a command, take a look to the cmdlet Show-Command.
Then, click on “Copy” to see the command (no positional or partial parameter, full cmdlet name, no alias):