gpt4 book ai didi

powershell - 多个强制性参数集

转载 作者:行者123 更新时间:2023-12-03 01:17:39 25 4
gpt4 key购买 nike

我正在研究一个包含多个参数集的函数,其中一些是必需的,而一些是可选的。

这只是一个示例,但请想象以下情况:

在AD组中添加或删除用户或计算机的功能(出于某种原因,您需要区分用户和计算机)。

请记住,这只是一个示例。在这种情况下,使用[string]来添加/删除单个ValidateSet()参数会容易得多,但这并不重要。

因此,您有4个参数集:

Param
(
[Parameter(ParameterSetName = 'Add', Mandatory = $true)][switch] $Add,
[Parameter(ParameterSetName = 'Remove', Mandatory = $true)][switch] $Remove,

[Parameter(ParameterSetName = 'User', Mandatory = $true)][switch] $User,
[Parameter(ParameterSetName = 'Computer', Mandatory = $true)][switch] $Computer
)

现在的问题是,您只能使用四个参数之一,而不能使用(添加或删除)和(用户或计算机)

我知道可以为每个参数使用多个参数集,但是我看不到一种强制它具有两个始终为强制性的参数集的方法。实际上,您必须始终指定“添加”或“删除”以及“用户”或“计算机”。

如何才能做到这一点?

最佳答案

您需要为这些不同的组合定义多个参数集。
试试这个:

Function TestParamSet {
[CmdletBinding()]
Param
(
[Parameter(ParameterSetName = 'AddUser', Mandatory = $true)]
[Parameter(ParameterSetName = 'AddComputer', Mandatory = $true)]
[switch] $Add,

[Parameter(ParameterSetName = 'RemoveUser', Mandatory = $true)]
[Parameter(ParameterSetName = 'RemoveComputer', Mandatory = $true)]
[switch] $Remove,

[Parameter(ParameterSetName = 'AddUser', Mandatory = $true)]
[Parameter(ParameterSetName = 'RemoveUser', Mandatory = $true)]
[switch] $User,

[Parameter(ParameterSetName = 'AddComputer', Mandatory = $true)]
[Parameter(ParameterSetName = 'RemoveComputer', Mandatory = $true)]
[switch] $Computer
)

Process {
#Do Nothing
}
}

而且,这是您获得有关此功能的帮助时看到的内容:
PS C:\> Get-Help TestParamSet 

NAME
TestParamSet

SYNTAX
TestParamSet -Add -Computer [<CommonParameters>]

TestParamSet -Add -User [<CommonParameters>]

TestParamSet -Remove -Computer [<CommonParameters>]

TestParamSet -Remove -User [<CommonParameters>]


ALIASES
None


REMARKS
None

关于powershell - 多个强制性参数集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com