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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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_Parametersand 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
-userexplicitly. 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: