Function overloading in PowerShell

powershell parameter sets
powershell polymorphism
powershell function parameters
powershell class method overload
powershell overloaddefinitions void close
powershell cannot find an overload
powershell object overload
about_functions_advanced_parameters

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-UsersData singleUser
  • Backup-UsersData @('Alice', 'Bob', 'Joe')
  • Backup-UsersData -all

In PowerShell functions are not overloaded. The last definition overrides the previous in the same scope or hides the previous in a parent scope. Thus, you should create a single function and provide a way to distinguish its call mode by arguments.

In V2 you may use an advanced function, see help about_Functions_Advanced_Parameters and avoid some manual coding on resolving parameter set ambiguities:

# advanced function with 3 parameter sets
function Backup-UsersData
(
    [Parameter(Position=0, ParameterSetName="user")]
    [string]$user,
    [Parameter(Position=0, ParameterSetName="array")]
    [object[]]$array,
    [Parameter(Position=0, ParameterSetName="all")]
    [switch]$all
)
{
    # use this to get the parameter set name
    $PSCmdlet.ParameterSetName
}

# test
Backup-UsersData -user 'John'
Backup-UsersData 1, 2
Backup-UsersData -all

# OUTPUT:
# user
# array
# all

Note that this mechanism is sometimes strange. For example in the first test we have to specify parameter name -user explicitly. Otherwise:

Backup-UsersData : Parameter set cannot be resolved using the specified named parameters.
At C:\TEMP\_101015_110059\try2.ps1:21 char:17
+ Backup-UsersData <<<<  'John'
    + CategoryInfo          : InvalidArgument: (:) [Backup-UsersData], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Backup-UsersData

In many cases standard, not advanced, function with mixed parameters will do:

function Backup-UsersData
(
    [string]$user,
    [object[]]$array,
    [switch]$all
)
{
    if ($user) {'user'}
    elseif ($array) {'array'}
    elseif ($all) {'all'}
    else {'may be'}
}

Backup-UsersData -user 'John'
Backup-UsersData -array 1, 2
Backup-UsersData -all
Backup-UsersData

But in this case you should resolve (or accept and ignore) ambiguities, e.g. to decide what to do if, say:

Backup-UsersData -user 'John' -array 1, 2 -all

Ad-hoc Polymorphism (Function Overloading) in PowerShell, PowerShell uses functions in a Session keyed on name so that you can only ever have a single function declared in your Runspace with a given  Each parameter set can be thought of as an overload (parameters can also be shared across all sets as shown below). There are a number of rules and features to parameter sets which can be found in §17.3.7 of the PowerShell v2 specification that I won’t bore you with today. Let’s create a function that computes the distance between two points.


Here is a variant of Roman's answer that I think is a little more flexible:

function Backup
{
    [CmdletBinding(DefaultParameterSetName='Users')]
    Param (
        [parameter(mandatory=$true, ParameterSetName='Users', position=0, ValueFromPipeline=$true)][string[]]$User,
        [parameter(mandatory=$true, ParameterSetName='AllUsers')][switch]$All
    )

    Begin
    {
        if ($All) { $User = @('User1', 'User2', 'User3') }
    }

    Process
    {
        foreach ($u in $User)
        {
            echo "Backup $u"
        }
    }
}

Function Overloading : PowerShell, I know powershell does not support function overloading. I also know that parameter sets are the psudo method of getting around this limitation. Is there any way  Here is an image of the overload output: Creating overloaded constructors. To create a constructor (overloaded or otherwise) in a Windows PowerShell 5.0 class, I need to remember that I am really creating a method. The method has the same name as the class name. When I do this, I have a constructor.


1) Build a class...

class c1 { 
    [int]f1( [string]$x ){ return 1 } 
    [int]f1( [int ]$x ){ return 2 }
    }

1+) Use STATIC METHODS if you prefer to call them without instantiation...

class c1 { 
    static [int] f1( [string]$x ){ return 1 } 
    static [int] f1( [int]$x ){ return 2 } 
    }

2) Call the methods in class or object... overload works OK

$o1 = [c1]::new()
o1.f1( "abc" ) ~> returns 1
o1.f1( 123 )   ~> returns 2

-OR-


[c1]::f1( "abc" ) ~> returns 1
[c1]::f1( 123 )   ~> returns 2

3) If (like me) you want to have "Overloaded Functions" placed in a libraries... so your users can use them transparently... from code or from Interactive Command Line (REPL)...

the closest I could came to "Overloading functions in Powershell" was something like this:

function Alert-String() { [c1]::f1( "abc" ) }
function Alert-Strings(){ [c1]::f1( 123 ) }
function Alert-Stringn(){ [c1]::f1( 123 ) }

Maybe in PS-Core v8??? ;-)

Hope it helps...

Example of a function overload in PowerShell _powershell, In PowerShell, we can use the Function keyword to define functions such as: Function Get-data { Param ( [int] $data =-1 ) return $data; } This  When will Powershell support overloading in plain functions (not OOP) This feature would be a great improvement and a code saver… right now to emulate function overload I have to recur to function parameter schemas or leverage some nice tricks with recursion…


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

PowerShell 5 Classes: Constructor Overloading, So for example, when I call a method and pass one or more parameters to it, that calls for an overloaded method definition. This means in the  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:


Topic: Function Overload, When will Powershell support overloading in plain functions (not OOP) This feature would be a great improvement and a code saver… Overloaded operators must either be a nonstatic class member function or a global function. A global function that needs access to private or protected class members must be declared as a friend of that class. A global function must take at least one argument that is of class or enumerated type or that is a reference to a class or enumerated type.


Overloading PowerShell Functions, year but, for whatever reason, the idea of overloading PowerShell functions (​which by the way, you can't officially do), seemed intriguing. Yes, you can override Get-ChildItem or any other cmdlet in Powershell. Name Your Function The Same. If you make a function with the same name in the same scope, yours will be used. Example: Function Get-ChildItem { [CmdletBinding()] param( # Simulate the parameters here ) # do stuff } Using Aliases


Using methods - Mastering Windows PowerShell Scripting, When the method is called without parentheses (the brackets), PowerShell will show the overload definitions. The overload definitions are a list of the different  PowerShell classes can have constructors. They have the same name as their class. Constructors can be overloaded. Static constructors are supported. Properties with initialization expressions are initialized before running any code in a constructor.