Is there a way to have some of the parameters mandatory based on some condition (for example, if one of the parameters is absent or false) in a PowerShell function?
My idea is to be able to call a function in two ways. A concrete example is a function that gets a list from SharePoint – I should be able to call it with relative URL of the list (one and only parameter) OR with a web URL and a list display name (two parameters, both mandatory, but only if list relative URL is not used).
As Christian indicated, this can be accomplished via ParameterSetNames. Take a look at this example:
If you run it with
-RelativeUrl Fooit will bind to “set1”. If you call this function without any parameters it will also bind to “set1”.(Note – when no parameters are provided in PowerShell v3 (with Windows 8 consumer preview) it will bind to “set1”, however it will error binding in PowerShell v2 unless you add
[CmdletBinding(DefaultParameterSetName="set1")]to the parameter block. Thanks @x0n for the DefaultParameterSetName tip!)If you try to run it with a parameter value from both sets you will get an error.
If you run it with
-WebUrl Barit will prompt you for a parameter value for DisplayName, because it’s a mandatory parameter.