This article describes two ways to define parameters for PowerShell custom functions, one is to place the list of arguments after the function name, just like other languages define function arguments, and the other is PowerShell unique way to use param keywords.
Let's take a look at the first way to define a parameter--after putting the list of arguments after the function name
For example, let's take a look at:
Copy Code code as follows:
function test-function ($ parameter Name 1 = ' Default parameter value 1 ', $ parameter Name 2 = ' Default parameter value 2 ')
{
Write-host "Parameters 1=$ parameter name 1, parameters 2=$ parameter name 2";
}
This approach is straightforward, and a bit like C # and PHP, you can assign a default value directly.
Microsoft tells us that this is not the best way to put a list of parameter definitions directly into the function name. When PowerShell is internally processed, it will further convert the parameter format defined above to the following official syntax:
Copy Code code as follows:
function test-function
{
PARAM ($ parameter name 1 = ' Default parameter value 1 ', $ parameter Name 2 = ' Default parameter value 2 ')
Write-host "Parameters 1=$ parameter name 1, parameters 2=$ parameter name 2";
}
Let's see the difference, take off the list of arguments immediately after the function name, along with the parentheses. Then in the function body (curly braces) to a section of param keyword start parameter definition code, put the argument list here. The other is unchanged.
Regardless of the way the parameter list is defined above, the results of the run are the same.
By the way, because the default value of the parameter is defined above, you can assign a value to the parameter at the time of the call, and you can assign a value. However, be sure to indicate the name of the parameter when assigning values. Such as:
Copy Code code as follows:
Ps> test-function
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
About the definition of PowerShell function parameters, this article on the introduction of so many, I hope to help you, thank you!