This article describes how to set the data type for a system to automatically recognize parameters when using a parameter set in PowerShell custom functions.
One advantage of identifying parameter types is that you do not need to specify the parameter names each time you use a parameter set.
Take a look at this test-binding function below. This PowerShell function sets the data type for the first argument in the set of parameters, so that when the function is invoked, it is possible to automatically determine which argument the parameter value should be assigned to.
Copy Code code as follows:
function Test-binding {
[Cmdletbinding (defaultparametersetname= ' Name ')]
Param
[Parameter (Parametersetname= ' ID ', position=0, mandatory= $true)]
[Int]
$id,
[Parameter (Parametersetname= ' Name ', position=0, mandatory= $true)]
[String]
$name
)
$set = $PSCmdlet. Parametersetname
"You selected $set parameter set"
if ($set-eq ' ID ') {
"The numeric ID is $id"
} else {
"You entered $name as a name"
}
}
Note that the parameter in the function $id [int] and the argument $name above [String]. With this kind of function definition, it's convenient for us to call, and if we pass a string to it, it will take this parameter as a $name and pass a number to it, and this parameter will be treated as $id. And look at the following example of calling a function.
Copy Code code as follows:
Ps> Test-binding-name Hallo
You selected Name parameter set
You entered Hallo as a name
Ps> Test-binding-id 12
You selected ID parameter set
The numeric ID is 12
Ps> test-binding Hallo
You selected Name parameter set
You entered Hallo as a name
Ps> test-binding 12
You selected ID parameter set
The numeric ID is 12
The above made 4 calls, the first two calls have specified the parameter name, there is nothing to say. The parameter name is not specified after two times, but the result of the execution is exactly the same as the previous two, which means that the PowerShell function automatically recognizes which parameter name the input parameter will call.
About PowerShell function parameter set automatic recognition parameter data type, this article introduces so many, hope to be helpful to you, thanks!