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.
Add a comment
|
2 Answers
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
}
}
}
Comments
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
)
...
}