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
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:
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:Note that this mechanism is sometimes strange. For example in the first test we have to specify parameter name
-user
explicitly. Otherwise:In many cases standard, not advanced, function with mixed parameters will do:
But in this case you should resolve (or accept and ignore) ambiguities, e.g. to decide what to do if, say:
Here is a variant of Roman's answer that I think is a little more flexible: