Function overloading in PowerShell

前端 未结 4 1667
温柔的废话
温柔的废话 2020-12-15 16:11

Can you overload functions in PowerShell?

I want to my function to accept a string, array or some switch.

An example of what I want:

  • Backup-Use
4条回答
  •  半阙折子戏
    2020-12-15 16:24

    If you use PSObject instead of Object to define your parameter type, it should work. For example, The function Get-Control, know's how to overload based on type string or template and can be called using the positional value:

        Get-Control "A-Name-Of-A-Control"
        Get-Control $template
    

    To make the overload work, use PSObject as follows:

    Function Get-Control {
        Param(
            [Parameter(Mandatory=$False,ParameterSetName="ByTemplate",Position=0)]
            [PSObject]
            $Template,
    
            [Parameter(Mandatory=$False,ParameterSetName="ByName",Position=0)]        
            [String]
            $Name,
    
            [Parameter(Mandatory=$False)] 
            [Switch]
            $List
          ) 
       ... # remaining code removed for brevity
    

提交回复
热议问题