Example of a function overload in PowerShell _powershell

Source: Internet
Author: User

In PowerShell, we can use the Function keyword to define functions such as:

Function Get-data {
 Param (
  [int] $data =-1
 ) return
 $data;
}

This function named Get-data receives a parameter $data of type int and returns it directly. Well, I also need a get-data function that receives the string type. The method is strange, at least unlike the traditional C + + languages.

To define an overloaded function in PowerShell, you specify the parameter Set that the parameter belongs to, as follows:

Function Global:get-data {
 Param (
  [Parameter (parametersetname= "Byint", position=0)] [int] $intData,
  [ Parameter (parametersetname= "Byswitch", position=0)] [switch] $boolData,
  [Parameter (parametersetname=) Byarray ", position=0)] [string[]] $arrayData
 )
 write-host $PsCmdlet. Parametersetname
}

It is not difficult to find that parametersetname specifies that each parameter belongs to the parameterset,position indicating that this is an anonymous parameter. And $pscmdlet.parametersetname represents the parameter Set that is currently in use. The use cases are as follows:

PS > Get-data 1
byint
PS > Get-data "a"
Byarray
ps > Get-data-booldata
byswitch

For more information on the PowerShell function parameters, see the relevant introduction on TechNet, or run the command in the PowerShell console: Help About_functions_advanced_parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.