PowerShell 7.3 - implementing Dynamic Parameters in Advanced Functions for Parameter Validation
I'm stuck trying to I'm creating an advanced function in PowerShell 7.3 that uses dynamic parameters to validate user input based on the value of another parameter. The goal is to have a main parameter that dictates the available options for a secondary parameter. However, I'm running into issues where the dynamic parameters are not showing up as expected, and I'm not sure why. Hereโs a simplified version of what I have: ```powershell function Get-CustomData { [CmdletBinding()] param ( [string]$Type, [Parameter(ValueFromPipeline=$true)] [string]$Name ) dynamicparam { $runtimeParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $validationAttribute = New-Object System.Management.Automation.ParameterAttribute $validationAttribute.Mandatory = $true if ($Type -eq 'User') { $parameter = New-Object System.Management.Automation.RuntimeDefinedParameter( 'UserId', [int], $validationAttribute ) $runtimeParamDictionary.Add('UserId', $parameter) } elseif ($Type -eq 'Group') { $parameter = New-Object System.Management.Automation.RuntimeDefinedParameter( 'GroupId', [int], $validationAttribute ) $runtimeParamDictionary.Add('GroupId', $parameter) } return $runtimeParamDictionary } process { if ($Type -eq 'User' -and $PSBoundParameters['UserId']) { Write-Output "Fetching data for User ID: $($PSBoundParameters['UserId'])" } elseif ($Type -eq 'Group' -and $PSBoundParameters['GroupId']) { Write-Output "Fetching data for Group ID: $($PSBoundParameters['GroupId'])" } else { Write-behavior "Invalid parameters provided." } } } ``` When I run `Get-CustomData -Type User -Name 'John'`, I expect it to prompt for `UserId`, but it seems that the dynamic parameter is not being set up correctly. I also tried explicitly defining the parameters in the dynamicparam block and ensuring that the conditions are met for the `Type`, but I still receive the following behavior: `Missing mandatory parameter 'UserId'.` I've validated that the `Type` parameter is being passed correctly, but it appears that the dynamic parameter isn't being recognized in the command context. I've also tried wrapping the dynamic parameter creation logic in conditions and placing debug statements but to no avail. Could anyone point out what I might be missing or if thereโs a better way to achieve this dynamic parameter validation? Thanks in advance!