Getting started with PowerShellLoopsOperatorsUsing ShouldProcessPowerShell ClassesSwitch statementWorking with ObjectsUsing existing static classesBasic Set OperationsPowerShell FunctionsSending EmailHandling Secrets and CredentialsPowershell RemotingPowerShell "Streams"; Debug, Verbose, Warning, Error, Output and InformationVariables in PowerShellCommunicating with RESTful APIsWorking with the PowerShell pipelinePowerShell Background JobsReturn behavior in PowerShellWorking with XML FilesIntroduction to PsakeUsing the progress barStringsTCP Communication with PowerShellSharePoint ModuleAliasesAutomatic VariablesEnvironment VariablesPowershell profilesEnforcing script prerequisitesUsing the Help SystemSplattingDesired State ConfigurationSigning ScriptsSecurity and CryptographyCSV parsingIntroduction to PesterModules, Scripts and FunctionsPowerShell.exe Command-LineCommon parametersParameter setsRegular ExpressionsPowerShell Dynamic ParametersWMI and CIMGUI in PowershellConditional logicURL Encode/DecodeMongoDBRunning ExecutablesError handlingHashTablesActiveDirectory modulepowershell sql queriesAutomatic Variables - part 2Package managementCmdlet NamingBuilt-in variablesCreating DSC Class-Based ResourcesPowershell ModulesPowerShell WorkflowsHow to download latest artifact from Artifactory using Powershell script (v2.0 or below)?Calculated PropertiesSpecial OperatorsAnonymize IP (v4 and v6) in text file with PowershellComment-based helpAmazon Web Services (AWS) Simple Storage Service (S3)Amazon Web Services (AWS) RekognitionPSScriptAnalyzer - PowerShell Script AnalyzerNaming ConventionsEmbedding Managed Code (C# | VB)Archive ModuleInfrastructure AutomationScheduled tasks moduleISE module

PowerShell Dynamic Parameters

Other topics

"Simple" dynamic parameter

This example adds a new parameter to MyTestFunction if $SomeUsefulNumber is greater than 5.

function MyTestFunction
{
    [CmdletBinding(DefaultParameterSetName='DefaultConfiguration')]
    Param
    (
        [Parameter(Mandatory=$true)][int]$SomeUsefulNumber
    )

    DynamicParam
    {
        $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
        $attributes = New-Object System.Management.Automation.ParameterAttribute
        $attributes.ParameterSetName = "__AllParameterSets"
        $attributes.Mandatory = $true
        $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
        $attributeCollection.Add($attributes)
        # If "SomeUsefulNumber" is greater than 5, then add the "MandatoryParam1" parameter
        if($SomeUsefulNumber -gt 5)
        {
            # Create a mandatory string parameter called "MandatoryParam1"
            $dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("MandatoryParam1", [String], $attributeCollection)   
            # Add the new parameter to the dictionary
            $paramDictionary.Add("MandatoryParam1", $dynParam1)
        }
        return $paramDictionary
    }

    process
    {
        Write-Host "SomeUsefulNumber = $SomeUsefulNumber"
        # Notice that dynamic parameters need a specific syntax
        Write-Host ("MandatoryParam1 = {0}" -f $PSBoundParameters.MandatoryParam1)
    }

}

Usage:

PS >  MyTestFunction -SomeUsefulNumber 3
SomeUsefulNumber = 3
MandatoryParam1 =

PS >  MyTestFunction -SomeUsefulNumber 6
cmdlet MyTestFunction at command pipeline position 1
Supply values for the following parameters:
MandatoryParam1:

PS >MyTestFunction -SomeUsefulNumber 6 -MandatoryParam1 test
SomeUsefulNumber = 6
MandatoryParam1 = test

In the second usage example, you can clearly see that a parameter is missing.

Dynamic parameters are also taken into account with auto completion.
Here's what happens if you hit ctrl + space at the end of the line:

PS >MyTestFunction -SomeUsefulNumber 3 -<ctrl+space>
Verbose              WarningAction        WarningVariable      OutBuffer
Debug                InformationAction    InformationVariable  PipelineVariable
ErrorAction          ErrorVariable        OutVariable

PS >MyTestFunction -SomeUsefulNumber 6 -<ctrl+space>
MandatoryParam1      ErrorAction          ErrorVariable        OutVariable
Verbose              WarningAction        WarningVariable      OutBuffer
Debug                InformationAction    InformationVariable  PipelineVariable

Contributors

Topic Id: 6704

Example Ids: 22811

This site is not affiliated with any of the contributors.