Erik Maldonado
Erik Maldonado

Reputation: 117

Why aren't optional parameters assigned positions? Powershell

Using the following example function:

Function Test {
  param(
    [Parameter(Position=0)]
    [string]$Optional="some optional string",
    [Parameter(Position=1, Mandatory=$true)]
    [string]$Required
  )
  Process { }
}

I would expect the following to be identical:

Test -Optional "optional" "required"

and

Test "required"

It's not, but why? The optional parameter is not mandatory, but the second example will fail saying:

Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.

It seems natural that if only one parameter is specified, that it would be the mandatory parameter because it needs to be specified.

Is there any way to accomplish what I am trying to do?

Upvotes: 3

Views: 541

Answers (1)

Ash
Ash

Reputation: 3266

When you give a parameter a position before a required one, it's not required, but it will be expected that the first input will be your optional parameter. To make your second example work, you just need to remove the Position reference for the non-required parameter. Of course, then Required would be the first position parameter or 0.

Function Test {
  param(
    [Parameter()]
    [string]$Optional,
    [Parameter(Position=0, Mandatory=$true)]
    [string]$Required
  )
  Process {
     Write-Host $Required
     if ($PSBoundParameters.ContainsKey('Optional')) {
        Write-Host $Optional -ForegroundColor Cyan
     }
  }
}

I added some output and removed the default value for the Optional parameter, so you can see what happens.

If you do not want to name the optional parameter, then you give it a position higher than the required parameters.

Function Test {
  param(
    [Parameter(Position=1)]
    [string]$Optional,
    [Parameter(Position=0, Mandatory=$true)]
    [string]$Required
  )
  Process {
     Write-Host $Required
     if ($PSBoundParameters.ContainsKey('Optional')) {
        Write-Host $Optional -ForegroundColor Cyan
     }
  }
}

About Functions Advanced Parameters

Upvotes: 1

Related Questions