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

By | May 22, 2015

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:

powershell parameter best practices

Note: The same logic also could be applied to attribute parameters (line 5)

===

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:

You will receive an error if the paramete is too ambiguous, in this case it could be -Pa(th) or -Pa(ssThru).

powershell parameter ambiguous path copy item

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 correct 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

Leave a Reply

Your email address will not be published.