Original article address:
Http://app.en25.com/e/es.aspx? S = 1403 & E = 5125 & elq = 52bc48204cc748d58a54ab9a57b6b796
Original article:
Adding parameters to your functions is fairly easy. You can add a param () block and specify the parameters. But what if you wanted to assign values to different parameters based solely on type? Let's say you want a function that accepts both numbers and text, and depending on which type you submitted, choose a parameter. Here is how you can do that:
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 parameterset $ set"
If ( $ Set -EQ 'Id' ){
"The numeric ID is $ id"
} Else {
"You entered $ name as a name"
}
}
Try this:
Test-binding 12
Test-binding "hello"
Test-binding
Translation:
It is very easy to add parameters in the method. You canParam ()CodeBlock to add the specified parameters. However, if you want to select which parameter is assigned the parameter value based on the parameter type? Assume that there is a method that can receive two parameters:NumbersAndTextWhich parameter is selected based on the content you submit? The implementation method is 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 parameterset $ set"
If ( $ Set -EQ 'Id' ){
"The numeric ID is $ id"
} Else {
"You entered $ name as a name"
}
}
Call method:
Test-binding 12
Test-binding "hello"
Test-binding
Notes:
This method is applicable to the assignment of dynamic parameters, provided that the parameter types must be different; otherwise, there will be ambiguity.