Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

function - Conditional PowerShell parameters

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...