0

Is it possible to create a [switch]-like parameter using DynamicParam? I know that I can just create a Boolean parameter, but in this case I will be forced to initialize its value like -BooParam $true, but I want to just type -BooParam. Why I need it - I would like to expose one switch parameter using Tab only if second is defined.

2 Answers 2

1

Yes, it is possible using DynamicParam:

function Test-Function
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$false)]
        [switch]$flag1

    )

    DynamicParam 
    {
         if ($flag1) 
         {
              $flag2 = New-Object System.Management.Automation.ParameterAttribute
              $flag2.Mandatory = $false
              $flag2.HelpMessage = "Only available if flag1 is set"

              $attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]              
              $attributeCollection.Add($flag2)

              $flag2param = New-Object System.Management.Automation.RuntimeDefinedParameter('flag2', [switch], $attributeCollection)

              $paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
              $paramDictionary.Add('flag2', $flag2param)
              return $paramDictionary
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Parameter sets might be a better (simpler) way to achieve your goal.

function Do-Something {
  [CmdletBinding(DefaultParameterSetName='none')]
  Param(
    ...
    [Parameter(ParameterSetName='set1', Mandatory=$true)]$Foo,
    [Parameter(ParameterSetName='set1')][Switch]$Bar
  )

  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.