1
votes

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.

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.

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
Requiring parameters in PowerShell when another parameter is present
PowerShell mandatory parameter depend on other parameter
Having a optional parameter that requires another paramter to be present
Multiple Mandatory Parameter Sets
Conditional powershell parameters

1
I could be completely wrong but it sounds like you are trying to get a function with two different signatures, which doesn't really make sense! Can't you just ignore the third parameter in your code if the first isn't specified? - 3-14159265358979323846264
@3-14159265358979323846264 I suppose I could keep $From and $Values optional then in the code after Param() I could say if (!$From - and !$Values) {Write-Error "Values must be provided if From not provided" Error-Action Stop}. Long day at work, I guess I was too preoccupied with processing within Param() to consider other possibilities like that. - NickSS

1 Answers

2
votes

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 has $Names and mandatory $Values
  • From has $From and optional $Values