Created
April 23, 2018 22:05
-
-
Save camusicjunkie/5e071b0f7a4f4d1730d5efafeaf2223a to your computer and use it in GitHub Desktop.
This file contains 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
Function New-DynamicParameter { | |
[cmdletbinding()] | |
param( | |
[Parameter(Mandatory)] | |
[ValidateNotNullOrEmpty()] | |
[string] $Name, | |
[string[]] $ValidateSet, | |
[System.Type] $Type = [string], | |
[string[]] $Alias, | |
[switch] $Mandatory = $false, | |
[string] $ParameterSetName = "__AllParameterSets", | |
[switch] $ValueFromPipeline = $false, | |
[switch] $ValueFromPipelineByPropertyName = $false, | |
[string] $HelpMessage, | |
[int] $Position = $null, | |
[ValidateScript({ | |
if (-not ($_ -is [System.Management.Automation.RuntimeDefinedParameterDictionary] -or -not $_)) { | |
Throw "DPDictionary must be a System.Management.Automation.RuntimeDefinedParameterDictionary object, or not exist" | |
} | |
$true | |
})] | |
$DPDictionary = $false | |
) | |
#Create attribute object, add attributes, add to collection | |
$ParamAttr = New-Object System.Management.Automation.ParameterAttribute | |
switch ($PSBoundParameters.Keys) { | |
'Mandatory' {$ParamAttr.Mandatory = $true} | |
'ValueFromPipeline' {$ParamAttr.ValueFromPipeline = $true} | |
'ValueFromPipelineByPropertyName' {$ParamAttr.ValueFromPipelineByPropertyName = $true} | |
'ParameterSetName' {$ParamAttr.ParameterSetName = $ParameterSetName} | |
'HelpMessage' {$ParamAttr.HelpMessage = $HelpMessage} | |
'Position' {$ParamAttr.Position = $Position} | |
} | |
$AttributeCollection = New-Object Collections.ObjectModel.Collection[System.Attribute] | |
$AttributeCollection.Add($ParamAttr) | |
#parameter validation set if specified | |
if ($PSBoundParameters.ContainsKey('ValidateSet')) { | |
$ParamOptions = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $ValidateSet | |
$AttributeCollection.Add($ParamOptions) | |
} | |
#Aliases if specified | |
if ($PSBoundParameters.ContainsKey('Alias')) { | |
$ParamAlias = New-Object System.Management.Automation.AliasAttribute -ArgumentList $Alias | |
$AttributeCollection.Add($ParamAlias) | |
} | |
#Create the dynamic parameter | |
$Parameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList @($Name, $Type, $AttributeCollection) | |
#Add the dynamic parameter to an existing dynamic parameter dictionary, or create the dictionary and add it | |
if ($PSBoundParameters.ContainsKey('DPDictionary')) { | |
$DPDictionary.Add($Name, $Parameter) | |
} | |
else { | |
$Dictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary | |
$Dictionary.Add($Name, $Parameter) | |
$Dictionary | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment