Božo Stojković
Božo Stojković

Reputation: 2943

Dynamic parameter doesn't work without CmdletBinding()

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

Upvotes: 3

Views: 396

Answers (1)

Božo Stojković
Božo Stojković

Reputation: 2943

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.

Upvotes: 3

Related Questions