[英]In a PowerShell function, how can I make a parameter mandatory only if another optional parameter is absent?
I'm writing a PowerShell function and I need the first parameter to be optional, then the third parameter to be optional but only if the first parameter is present. 我正在编写PowerShell函数,我需要第一个参数为可选,然后第三个参数为可选,但前提是第一个参数存在。
Here is the code as it is right now: 这是现在的代码:
Param(
[Parameter(position=0)][array]$From,
[Parameter(position=1,Mandatory=$true)][string[]]$Names,
[Parameter(position=2)][string[]]$Values
)
Ideally I would do this: 理想情况下,我会这样做:
[Parameter(position=2,Mandatory=(!$From))][string[]]$Values
But that is not allowed. 但这是不允许的。
I've been getting the impression that using set names in some way is the way to go, but I'm not sure how I would go about it. 我一直在以某种方式使用集合名称的印象,但是我不确定该如何处理。 The only thing I need to change is the Mandatory attribute value for $Values depending on the existence of $From.
我唯一需要更改的是$ Values的强制属性值,具体取决于$ From的存在。
What is the best way for me to do this? 我这样做的最佳方法是什么?
I've looked over each of the following past questions pretty thoroughly and nothing I tried based on what I found in them would work. 我已经仔细研究了以下每个过去的问题,但根据发现的问题我尝试过的任何方法都行不通。
Create a function with optional call variabls: Powershell 创建带有可选调用变量的函数:Powershell
Requiring parameters in PowerShell when another parameter is present 存在另一个参数时在PowerShell中要求参数
PowerShell mandatory parameter depend on other parameter PowerShell强制参数取决于其他参数
Having a optional parameter that requires another paramter to be present 具有一个可选参数,需要提供另一个参数
Multiple Mandatory Parameter Sets 多个强制性参数集
Conditional powershell parameters 条件Powershell参数
Try something like this: 尝试这样的事情:
[Parameter(position=0,ParameterSetName = "From")]
[array]$From,
[Parameter(position=1,Mandatory=$true,ParameterSetName = "Names")]
[string[]]$Names,
[Parameter(position=2,Mandatory=$true,ParameterSetName = "Names")]
[Parameter(position=2,Mandatory=$false,ParameterSetName = "From")]
[string]$Values
You define two sets, Names
and From
您定义两个集合,
Names
和From
Names
has $Names and mandatory $Values Names
包含$ Names和必需的$ Values From
has $From and optional $Values From
具有$ From和可选的$ Values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.