Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic parameter doesn't work without CmdletBinding()

Tags:

powershell

The parameter doesn't seem to be "set" as a parameter at all. Validate set doesn't work. Neither does autocomplete. Typing in the parameter name doesn't work either.

I know I did dynamic parameters before. But this time, I'm missing something. Just can't figure out what it is.

Function Add-Control() {
    DynamicParam {
        $ParamAttribute = New-Object Parameter
        $ParamAttribute.Mandatory = $true
        $ParamAttribute.ParameterSetName  = '__AllParameterSets'

        $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

        $AttributeCollection.Add($ParamAttribute)

        $controlTypes = @("TextBox", "Label", "DataGrid")

        $AttributeCollection.Add((New-Object ValidateSet($controlTypes)))

        $RuntimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter('Type', [string], $AttributeCollection)

        $RuntimeParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

        $RuntimeParamDictionary.Add('Type', $RuntimeParam)

        return $RuntimeParamDictionary
    }

    Process {
        Write-Host ($PSBoundParameters['Type'])
    }
}

Add-Control -Type "Test"
# $null
like image 988
Božo Stojković Avatar asked Apr 08 '26 03:04

Božo Stojković


1 Answers

Not sure if this is a stupid mistake, but I surely feel that way. I was missing

[CmdletBinding()]
Param()

Both validate set and autocomplete work now.

Hopefully this helps others.

like image 138
Božo Stojković Avatar answered Apr 10 '26 02:04

Božo Stojković



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!