![](/img/trans.png)
[英]In a PowerShell function, how can I make a parameter mandatory only if another optional parameter is absent?
[英]Powershell function - parameter has to be mandatory in one case, optional in another
我有这个功能:
function AlwaysRunAtLogon {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[System.String]$NomTache,
[Parameter(Mandatory = $true)]
[System.String]$Script,
[switch]$retrait
)
...
}
用例1是:
AlwaysRunAtLogon -NomTache AnyName C:\temp\script.ps1
它将运行代码以添加某些内容。 一切正常。 现在,我想向函数添加SWITCH参数,以便它可以根据第一个参数(NomTache)的值删除某些内容
因此,用例2将是:
AlwaysRunAtLogon -NomTache AnyName -Retrait
现在这是问题所在。 在情况#1中,我想保持$ Script为强制性,以便用户必须提供脚本文件。 但是,在情况2中,$ Script现在是可选的,因为删除操作只需要第一个参数即可工作(NomTache)
如何调整此功能,以便可以同时使用案例1和2? 某处可能存在逻辑问题。 我是函数新手,非常感谢您的帮助。 我愿意进行任何重新设计。
我是否最好执行另一个功能,例如“ RemoveAlwaysRunAtLogon”并像这样运行它? :
RemoveAlwaysRunAtLogon -NomTache AnyName
您可以使用ParameterSets
解决您的问题。
不知道我是否完全理解您的要求,所以这只是一个例子。 但是我认为模型很明确。
function AlwaysRunAtLogon {
[CmdletBinding()]
param (
[Parameter(
ParameterSetName='Name1',
Mandatory=$true
)]
[Parameter(
ParameterSetName='Name2',
Mandatory=$true
)]
[System.String]$NomTache,
[Parameter(
ParameterSetName='Name1',
Mandatory = $true
)]
[System.String]$Script,
[Parameter(
ParameterSetName='Name2'
)]
[switch]$retrait
)
...
}
感谢上面的vrdse使它像这样工作:
function AlwaysRunAtLogon {
[CmdletBinding()]
param (
[Parameter(ParameterSetName='Ajout',Mandatory=$true)]
[Parameter(Position=0,ParameterSetName='Retrait',Mandatory=$true)]
[System.String]$Nom,
[Parameter(Position=1,ParameterSetName='Ajout',Mandatory = $true)]
[System.String]$Script,
[Parameter(ParameterSetName='Retrait')]
[switch]$retrait
)
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.