条件 PowerShell 参数 [英] Conditional PowerShell parameters
问题描述
有没有办法根据 PowerShell 函数中的某些条件(例如,如果其中一个参数不存在或为假)强制某些参数?
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?
我的想法是能够以两种方式调用函数.一个具体的例子是一个从 SharePoint 获取列表的函数 - 我应该能够使用列表的相对 URL(一个且唯一的参数)或使用 Web URL 和列表显示名称(两个参数,都是必需的,但是仅当未使用列表相对 URL 时).
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).
推荐答案
正如 Christian 所指出的,这可以通过 ParameterSetNames 来完成.看看这个例子:
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)
}
如果您使用 -RelativeUrl Foo
运行它,它将绑定到set1".如果你不带任何参数调用这个函数,它也会绑定到set1".
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".
(注意 - 当 PowerShell v3(带有 Windows 8 消费者预览版)中没有提供参数时,它将绑定到set1",但是它会在 PowerShell v2 中错误绑定,除非您将 [CmdletBinding(DefaultParameterSetName="set1")]
添加到参数块.感谢 @x0n 提供 DefaultParameterSetName 提示!)
(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.
如果您使用 -WebUrl Bar
运行它,它会提示您输入 DisplayName 的参数值,因为它是必需参数.
If you run it with -WebUrl Bar
it will prompt you for a parameter value for DisplayName, because it's a mandatory parameter.
这篇关于条件 PowerShell 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!