有条件的PowerShell参数 [英] Conditional powershell parameters

查看:145
本文介绍了有条件的PowerShell参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在powershell函数中根据某些条件强制某些参数(例如:如果其中一个参数不存在或为false)



我的想法是能够以两种方式调用函数。具体的例子是从Sharepoint获取列表的函数 - 我应该能够使用列表相对url(一个且唯一的参数)或者使用web url和列表显示名称(两个参数,都是必需的,但只有当列表相对url是未使用)。



我希望我的问题很清楚。

解决方案

正如Christian指出的,这可以通过ParameterSetNames完成。看看这个例子:

 函数Get-MySPWeb {
[CmdletBinding(DefaultParameterSetName =set1)]
param(
[parameter(ParameterSetName =set1)] $ RelativeUrl,
[parameter(ParameterSetName =set2)] $ WebUrl,
[parameter(ParameterSetName = (参数设置在操作中:+ $ PSCmdlet.ParameterSetName)
Write-Host(RelativeUrl:+PS2)
写入主机(Set2,Mandatory = $ true)] $ DisplayName
) (WebUrl:+ $ WebUrl)
Write-Host(DisplayName:+ $ DisplayName)


如果使用 -RelativeUrl Foo 运行它,它将绑定到set1 。如果你没有参数调用这个函数,它也会绑定到set1。


$ b

注意 - 在PowerShell v3中没有提供参数时(使用Win8使用者预览),它将绑定到set1但是它会在PowerShell v2中出现错误绑定,除非你在param块中添加 [CmdletBinding(DefaultParameterSetName =set1)] 。谢谢@ x0n用于DefaultParameterSetName tip!



如果您尝试使用两个集合中的参数值运行它,您将会收到错误消息。

如果你使用 -WebUrl Bar 运行它,它会提示你为DisplayName指定一个参数值,因为它是一个必需参数。


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 powershell function?

My idea is to be able to call function in two ways. Concrete example is function that gets list from sharepoint - I should be able to call it with list relative url (one and only parameter) OR with web url and and list display name (two params, both mandatory, but only if list relative url is not used).

I hope my question is clear.

解决方案

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 with no parameters it will also bind to "set1".

(Note - when no parameters are provided in PowerShell v3 (with Win8 consumer preview) it will bind to "set1", however it will error binding in PowerShell v2 unless you add [CmdletBinding(DefaultParameterSetName="set1")] to the param 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.

这篇关于有条件的PowerShell参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆