powershellparameter-passingparameter-sets

How to make one of two parameters mandatory, so that at least one of the two is always present?


mandatory would make both parameters required. I just need to make sure either path or fileList is always present.

I have been making do with the following but its not ideal:

function foo{
    Param(
    [string[]]$path
    [string[]]$fileList
    )
    if (($null -eq $path) -and ($fileList -eq "")){Write-Error -Message "Paths or FilieList must be used" -ErrorAction Stop}
}

win11/pwsh 7.4


Solution

  • Try the following:

    function foo {
      [CmdletBinding(DefaultParameterSetName = 'PathAndFileList')]
      Param(
    
        [Parameter(ParameterSetName='PathOnly', Mandatory)]
        [Parameter(ParameterSetName='PathAndFileList', Mandatory)]
        [string[]]$Path,
    
        [Parameter(ParameterSetName='FileListOnly', Mandatory)]
        [Parameter(ParameterSetName='PathAndFileList', Mandatory)]
        [string[]]$FileList
    
      )
      # Diagnostic output: Show which parameters were bound.
      $PSBoundParameters
    }
    

    The key is to use parameter sets: