Powershell Best Practice #2: Use named parameter (not positional and partial parameter)

By | May 22, 2015

Best Practice: It is recommended to use named parameter, avoid positional and abbreviated/truncated/shortened/partial parameter names in your scripts.

Explanation: Positional and partial parameter names can be used for the interactive Powershell console to speed up our work, but not in scripts.

It takes more time to write the named parameter but your code will be more clear and consistent.

Positional parameters can be more difficult to read especially with cmdlets supporting multiple parameters.
Besides, the command will fail if the correct order is not respected (parameter order mixed up).

Moreover, with future versions of Powershell there is no guarantee that these parameters keep the same position.
A script created using positional parameters in the past could have a different behaviour in the future, but with named parameters there is no issue.

You can use Show-Command to see the Best Practice action as it will use the full cmdlet name and the named parameter.

Positional parameters are created that way:

Regarding partial parameter name (or parameter arguments), you will receive an error if the parameter/argument is too ambiguous:

P   =>PowerShell found matches for -PassThru -Path -PipelineVariable -LiteralPath.
Pa => PowerShell found matches for -PassThru -Path
Pat => PowerShell found match for -Path only

-ErrorAction S  => PowerShell found match for SilentlyContinue, Stop, Suspend
-ErrorAction Si => PowerShell found match for SilentlyContinue only

partial-parameter-name-arguments-ambiguous

Note: You can also create an alias for a parameter.

Main benefits of parameter aliases:

  1. Backwards compatibility (if you rename a parameter ‘NewParameter’, you can add a parameter alias to the old name ‘OldParameter’)
  2. Multiple possible names (you can have multiple names for a same parameter : CN, ComputerName, …)
  3. Shortcut to the parameter (you can type -CN instead of -ComputerName)

alias-parameter-powershell

Note: If you want to see the Best Practice way to write a command, take a look to the cmdlet Show-Command.

show-command-copy-command

Then, click on “Copy” to see the command (no positional or partial parameter, full cmdlet name, no alias):

show-command-copy-command-powershell


previous-buttonnext-button

2 thoughts on “Powershell Best Practice #2: Use named parameter (not positional and partial parameter)

  1. Pingback: Powershell Best Practice #1: Use full cmdlet name (not alias) | Powershell Guru

  2. Pingback: Powershell Best Practice #3: Use Write-Output (not Write-Host) | Powershell Guru

Leave a Reply

Your email address will not be published. Required fields are marked *