Conditional PowerShell parameters
conditional-statements, function, parameters, powershell
Solution
As Christian indicated, this can be accomplished via ParameterSetNames. Take a look at this example:
function Get-MySPWeb {
[CmdletBinding(DefaultParameterSetName="set1")]
param (
[parameter(ParameterSetName="set1")] $RelativeUrl,
[parameter(ParameterSetName="set2")] $WebUrl,
[parameter(ParameterSetName="set2", Mandatory=$true)] $DisplayName
)
Write-Host ("Parameter set in action: " + $PSCmdlet.ParameterSetName)
Write-Host ("RelativeUrl: " + $RelativeUrl)
Write-Host ("WebUrl: " + $WebUrl)
Write-Host ("DisplayName: " + $DisplayName)
}
If you run it with `-RelativeUrl Foo` it 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 Bar` it will prompt you for a parameter value for DisplayName, because it's a mandatory parameter.
Problem
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).