This article introduces two methods for customizing functions to define parameters of PowerShell. One is to place the parameter list after the function name, which is the same as other languages define function parameters; the other is the unique method of PowerShell, which is to use the param keyword.
Let’s take a look at the first way to define parameters - put the parameter list after the function name
Let’s take a look at this example:
function Test-Function($ parameter name 1='default parameter value 1', $ parameter name 2='default parameter value 2')
{
Write-Host "Parameter 1=$parameter name 1, parameter 2=$parameter name 2";
}
This method is simple and direct, and it is a bit like C# and PHP, and you can directly assign default values.
Microsoft told us that this is not the best way to put the list of parameter definitions directly into the function name. When PowerShell is processed internally, it will further convert the parameter format defined above into the following official syntax:
function Test-Function
{
param($ parameter name 1='default parameter value 1', $ parameter name 2='default parameter value 2')
Write-Host "Parameter 1=$parameter name 1, parameter 2=$parameter name 2";
}
Everyone can see the difference, just remove the parameter list after the function name together with brackets. Then, in the function body (within braces), a parameter definition code starting with the param keyword is put here. The others remain unchanged.
No matter which way of defining the parameter list above, the results of the operation are the same.
By the way, because the default value of the parameter is defined above, the parameter can be assigned when called, and no value can be assigned. However, when assigning values, you must specify the name of the parameter. like:
Parameter 1 = default parameter value 1, parameter 2 = default parameter value 2
PS> Test-Function - Parameter 1 "p1"
Parameter 1=p1, Parameter 2=Default parameter value 2
This article introduces so much about PowerShell function parameter definition. I hope it will be helpful to you. Thank you!