Skip to content

Instantly share code, notes, and snippets.

@mrhockeymonkey
Created February 12, 2020 09:38
Show Gist options
  • Save mrhockeymonkey/8ff4c8c31971f7a69eb3ce0efca692c3 to your computer and use it in GitHub Desktop.
Save mrhockeymonkey/8ff4c8c31971f7a69eb3ce0efca692c3 to your computer and use it in GitHub Desktop.
Dynamically define dynamic parameters for Powershell functions
function Verb-Noun {
[CmdletBinding()]
param (
# a normal parameter
[Parameter(ValueFromPipeline = $true)]
[System.String]$Name,
)
dynamicparam {
# a simple dynamic parameter, $PossibleCategories is discovered on module import
$DynamicParams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$Param1 = New-Object System.Management.Automation.RuntimeDefinedParameter
$Param1Attr = New-Object System.Management.Automation.ParameterAttribute
$Param1Validation = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList ($PossibleCategories | Select-Object -ExpandProperty Name)
$Param1.Name = 'CategoryName'
$Param1.ParameterType = [System.String]
$Param1Attr.Mandatory = $true
$Param1.Attributes.Add($Param1Attr)
$Param1.Attributes.Add($Param1Validation)
$DynamicParams.Add('CategoryName', $Param1)
# dynamically defined dynamic params, $PossibleAttributesHash again discovered on module import
$Script:PossibleAttributesHash.GetEnumerator() | ForEach-Object {
$Param1 = New-Object System.Management.Automation.RuntimeDefinedParameter
$Param1Attr = New-Object System.Management.Automation.ParameterAttribute
$Param1Validation = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $Script:PossibleAttributesHash[$_.Key]
$Param1.Name = $_.Key
$Param1.ParameterType = [System.String]
#when adding a new machine site is manatory
if ($_.Key -in 'site') {
$Param1Attr.Mandatory = $true
} else {
$Param1Attr.Mandatory = $false
}
$Param1.Attributes.Add($Param1Attr)
$Param1.Attributes.Add($Param1Validation)
$DynamicParams.Add($_.Key, $Param1)
}
Return $DynamicParams
}
begin {}
process {}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment