Functions/Scripting/Parametrics/New-DynamicParameter.ps1

<#
.Synopsis
   This script creates a dynamic runtime parameter.
.DESCRIPTION
   This script creates a dynamic runtime parameter that can attached to a RuntimeParameterDictionary
   inside of a dynamicparam block for better cmdlet construction.
   It takes in Parameter Name, Position, Dataset (to enumerate in the dynamic parameter) and the mandatory status.
.EXAMPLE
   New-DynamicParameter -ParamName VMHost -Dataset @((get-vmhost).name)
.EXAMPLE
   New-DynamicParameter -ParamName VMHost -Dataset @((get-vmhost).name) -Mandatory $True -Position 0
#>

function New-DynamicParameter
    {
    [CmdletBinding()]
    Param
        (
        # Name of Dynamic Parameter
        [Parameter(Mandatory=$true)]
        [string]
        $ParamName,

        # Value Type of Dynamic Parameter
        [Parameter(Mandatory=$true)]
        [ValidateSet([string],[string[]],[int],[int[]],[boolean])]
        $ValueType,

        # Data array to select Dynamic Parameter value from
        [Parameter(Mandatory=$true)]
        [array]
        $DataSet,

        # Mandatory Status of Dynamic Parameter
        [Parameter(Mandatory=$false)]
        [Boolean]
        $Mandatory = $true,

        # Default Value of Dynamic Parameter
        [Parameter(Mandatory=$false)]
        $DefaultValue,

        # Pipeline Enablement Status of Dynamic Parameter
        [Parameter(Mandatory=$false)]
        [boolean]
        $ValueFromPipeLine = $false,

        # Parameter Set Name Associated with Dynamic Parameter
        [Parameter(Mandatory=$false)]
        [string]
        $ParameterSetName,

        # Position of Dynamic Parameter
        [Parameter(Mandatory=$false)]
        [int]
        $Position
        )

    Process
        {
        $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
        $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
        $ParameterAttribute.Mandatory = $Mandatory
        $ParameterAttribute.ValueFromPipeline = $ValueFromPipeLine
        if($position) {$ParameterAttribute.Position = $Position}
        if($ParameterSetName) {$ParameterAttribute.ParameterSetName = $ParameterSetName}
        $AttributeCollection.Add($ParameterAttribute) 
        $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($DataSet)    
        $AttributeCollection.Add($ValidateSetAttribute)
        $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParamName,$ValueType,$AttributeCollection)
        if (!$Mandatory -and $DefaultValue) {$RuntimeParameter.Value = $DefaultValue}
        Return $RuntimeParameter
        }
    }