This article describes whether PowerShell custom functions support overloading, and if so, how do I overload them? If not, how do I achieve the same effect as overloading?
Solemnly declare: PowerShell Custom function does not support overloading! In other words, you cannot define two PowerShell functions with the same name, regardless of the number, order, or type of the parameters. Since the PowerShell custom function does not support overloaded functionality, is there any way to achieve the same effect as overloading? Yes, of course there is, that's the parameter set (Parameters set)
The set of parameters for a PowerShell custom function can define a parameter set for a function that can be used by selecting a parameter from a parameter set when calling a function. Note that you can only select one from the parameter set to use. Let's take a look at this example and have a perceptual understanding of the parameters set.
Copy Code code as follows:
function Add-user
{
[Cmdletbinding (defaultparametersetname= ' A ')]
Param
(
[Parameter (Parametersetname= ' A ', mandatory= $true)]
$Name,
[Parameter (Parametersetname= ' B ', mandatory= $true)]
$SAMAccountName,
[Parameter (Parametersetname= ' C ', mandatory= $true)]
$DN
)
$chosen = $PSCmdlet. Parametersetname
"You have chosen $chosen parameter set."
}
The Add-user function above defines a set of parameters with three parameters in the set: Name, sAMAccountName, DN, which can be selected by any one of them. However, the Add-user function can only pass one argument.
Copy Code code as follows:
Ps> add-user-name Test
You have chosen A parameter set.
Ps> add-user-samaccountname Test
You have chosen B parameter set.
Ps> ADD-USER-DN Test
You have chosen C parameter set.
ps> ADD-USER-DN test-name Test
Add-user:parameter set cannot be resolved using the specified named parameters.
Hongo For example, we're going to do a function that wants to output news content through news IDs or news headlines. So how should it be achieved?
Copy Code code as follows:
function get-newscontent
{
[Cmdletbinding (defaultparametersetname= ' A ')]
[Parameter (Parametersetname= ' A ', mandatory= $true)]
$NewsID,
[Parameter (Parametersetname= ' B ', mandatory= $true)]
$NewsTitle
$chosen = $PSCmdlet. Parametersetname
If ($chosen-eq "A") {
"News Content by NewsID"
}else{
"News Content by Newstitle"
}
}
About the PowerShell function support overload, this article on the introduction so much, I hope to help you, thank you!