Динамический параметр для validateset и условный параметр, основанный на значении динамического validateset - PullRequest
0 голосов
/ 02 июля 2019

Можно ли использовать функцию динамического параметра PowerShell для создания как параметра validateset, так и условного параметра на основе значения этого параметра?

В сценарии я использую динамический параметр, чтобы сгенерировать параметр, который вычисляется с помощью validateset. Я хочу добавить в скрипт условный параметр, который требуется только на основе значения в validateset.

Вот пример кода для того, что я пытаюсь выполнить. В этом примере кода условный параметр никогда не создается, потому что $PSBoundParameter.Product никогда не устанавливается в блоке DynamicParam. Возможно ли что-то подобное с PowerShell?

function Get-Order {
    [CmdletBinding()]
    Param(
        [Parameter(
            Mandatory=$true,
            Position=1,
            HelpMessage="How many cups would you like to purchase?"
        )]
        [int]$cups
    )

    DynamicParam {
        Write-Warning "This gets printed"
        ## Product parameter with dynamic ValidateSet
        $productAttribute = new-object System.Management.Automation.ParameterAttribute
        $productAttribute.Position = 2
        $productAttribute.Mandatory = $false
        $productAttribute.HelpMessage = "What would you like to purchase?"

        #create an attributecollection object for the attribute we just created.
        $attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]

        #add our custom attribute
        $attributeCollection.Add($productAttribute)

        #add our paramater specifying the attribute collection
        $arrSet = @("Lemonade","Water","Tea","Coffee","Hard Lemonade") # In my actual script this is generated not hard coded.
        $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
        $AttributeCollection.Add($ValidateSetAttribute)

        $productParam = new-object -Type System.Management.Automation.RuntimeDefinedParameter("Product", [string], $attributeCollection)

        #expose the name of our parameter
        $paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $paramDictionary.Add('Product', $productParam)

        if ($PSBoundParameters.Product -eq "Hard Lemonade") {
              Write-Warning "Never printed"
              #create a new ParameterAttribute Object
              $ageAttribute = New-Object System.Management.Automation.ParameterAttribute
              $ageAttribute.Position = 3
              $ageAttribute.Mandatory = $true
              $ageAttribute.HelpMessage = "This product is only available for customers 21 years of age and older. Please enter your age:"

              #create an attributecollection object for the attribute we just created.
              $attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]

              #add our custom attribute
              $attributeCollection.Add($ageAttribute)

              #add our paramater specifying the attribute collection
              $ageParam = New-Object System.Management.Automation.RuntimeDefinedParameter('age', [Int16], $attributeCollection)

              #expose the name of our parameter
              $paramDictionary.Add('age', $ageParam)
        }

        return $paramDictionary
    }

    Process {
        $order = @()
        for ($cup = 1; $cup -le $cups; $cup++) {
            $order += "$($cup): A cup of $($product)"
        }
        $order
    }
}

Примечание. Этот код основан на примере кода из PowerShellMagazine .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...