CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Trouble with Dynamic Parameter Binding in Custom Cmdlet

👀 Views: 79 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
PowerShell cmdlet dynamic-parameters

I'm a bit lost with I've been researching this but I tried several approaches but none seem to work... Quick question that's been bugging me - I'm sure I'm missing something obvious here, but I'm trying to create a custom cmdlet in PowerShell 7.3 that uses dynamic parameters to allow users to specify additional options based on the input type. However, I'm working with issues with the dynamic parameter binding not functioning as expected. Here's a simplified version of what I've implemented: ```powershell [CmdletBinding()] param( [string]$InputType ) dynamicparam { $runtimeParams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary if ($InputType -eq 'File') { $param = New-Object System.Management.Automation.RuntimeDefinedParameter( 'FilePath', [string], $null ) $runtimeParams.Add('FilePath', $param) } elseif ($InputType -eq 'Folder') { $param = New-Object System.Management.Automation.RuntimeDefinedParameter( 'FolderPath', [string], $null ) $runtimeParams.Add('FolderPath', $param) } return $runtimeParams } process { if ($InputType -eq 'File') { Write-Host "File Path: $($PSBoundParameters['FilePath'])" } elseif ($InputType -eq 'Folder') { Write-Host "Folder Path: $($PSBoundParameters['FolderPath'])" } } ``` When I run this cmdlet with `-InputType File -FilePath 'C:\example.txt'`, I expect it to output the file path, but I receive the following behavior: ``` want to bind argument to parameter 'FilePath' because it is null. ``` I've verified that the dynamic parameters are being defined correctly, but it seems that they are not being set when I call the cmdlet. I've also tried using `Write-Verbose` to debug and confirm if the dynamic parameters are being recognized, but they don't seem to appear in the `$PSBoundParameters` hashtable. Could anyone provide insights into what might be going wrong or best practices for implementing dynamic parameters with input validation in PowerShell 7.3? Any help would be greatly appreciated! Is there a better approach? What am I doing wrong? I'm working on a microservice that needs to handle this. Has anyone dealt with something similar? What am I doing wrong?