Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't optional parameters assigned positions? Powershell

Tags:

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?

like image 897
Erik Maldonado Avatar asked Jul 21 '26 11:07

Erik Maldonado


1 Answers

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

like image 59
Ash Avatar answered Jul 25 '26 00:07

Ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!