Functions/Scripting/Parametrics/Initialize-DynamicParameters.ps1
<#
.Synopsis This script creates parent-scoped variables for each of the dynamic parameters that are defined in a scripts RuntimeParameterDictionary. .DESCRIPTION The normal mechanism of passing defined dynamic parameter values into the $PSBoundParameters dictionary during runtime is not optimal. It does not allow the passing forward of any default values for non-mandatory dynamic parameters even though they can be defined in the RunTimeParameterDictionary. So this function which should be run in the Begin {} scriptblock will make sure that all dynamic parameters have a variable created for them in the parent function/script just like the static parameters already do. Additionally, if there are any default values on non-mandatory dynamic parameters that have been defined in the Dynamic Parameter Dictionary but were not explicitly set during the execution the script, they will also have parent scope variables created for them in order for those default values to be available to the rest of the script. This is a feature! Utilitizing this function requires a little bit of trust during development in an IDE like PSISE as you have to trust your variables from the dynamic parameters to be available during runtime but they will not necessarily be written into your script in such a way that they are visible to you before you try and use them as you get with the appearance of the variables created from your static params. It takes in DynamicDictionary ($RuntimeParameterDictionary from the DynamicParam Block in most scripts) This is also very meta... .EXAMPLE Initialize-DynamicParameters -DynamicDictionary $RuntimeParameterDictionary #> function Initialize-DynamicParameters { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [System.Management.Automation.RuntimeDefinedParameterDictionary] $DynamicDictionary ) Process { foreach ($key in [array]($DynamicDictionary.Keys)) { if ($dynamicdictionary.$key.IsSet) { New-Variable -Name $key -Value $DynamicDictionary.$key.value -Scope 1 -Force $VAR = try{Get-Variable -Name $key -Scope 1 -ErrorAction Stop}catch{$null} if(!$VAR){write-host "WTF?" -ForegroundColor Red} } } } } |