Created
October 12, 2020 02:42
-
-
Save mabster/494109ba67c177806db7fb364b58f446 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[cmdletbinding()] | |
param ( | |
[parameter(parametersetname='test1')] | |
[switch]$p1, | |
[parameter(parametersetname='test2')] | |
[switch]$p2 | |
) | |
DynamicParam | |
{ | |
switch ($pscmdlet.parametersetname) { | |
test1 | |
{ | |
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] | |
$attributes = New-Object -Type System.Management.Automation.ParameterAttribute | |
$attributes.ParameterSetName = "test1" | |
$attributes.Mandatory = $false | |
$attributeCollection.Add($attributes) | |
$attributes = New-Object -Type System.Management.Automation.ValidateRangeAttribute(1, 3) | |
$attributeCollection.Add($attributes) | |
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Count", [Int32], $attributeCollection) | |
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary | |
$paramDictionary.Add("Count", $dynParam1) | |
return $paramDictionary | |
} | |
test2 | |
{ | |
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] | |
$attributes = New-Object -Type System.Management.Automation.ParameterAttribute | |
$attributes.ParameterSetName = "test2" | |
$attributes.Mandatory = $false | |
$attributeCollection.Add($attributes) | |
$attributes = New-Object -Type System.Management.Automation.ValidateRangeAttribute(1, 10) | |
$attributeCollection.Add($attributes) | |
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Count", [Int32], $attributeCollection) | |
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary | |
$paramDictionary.Add("Count", $dynParam1) | |
return $paramDictionary | |
} | |
} | |
} | |
process { | |
write-output $psboundparameters.Count | |
} |
Yeah that's a really good point. Mine was very hurriedly put together by copying and pasting from blog posts. Yours is already much more succinct!
In fact there may not even be a need to assign a valid to $attributes.ParameterSetName, since in Dave's cmdlet the parameter was available all the time. Even less code!
Thanks guys.
Definitely something to look into over the next few days.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saw this on the Twitter thread, super cool! @thedavecarroll to you point about it being a lot of code... yes, but you can make it so that only the unique stuff is inside the switch statement and everything else is outside and only specified once.