Can I make a parameter set depend on the value of another parameter?

后端 未结 2 989
北恋
北恋 2021-01-22 09:12

Let\'s say I have a function like:

function Authenticate
{
  param
  (
    [ValidateSet(\'WindowsAuthentication\',\'UsernameAndPassword\')][string] $Authenticati         


        
2条回答
  •  误落风尘
    2021-01-22 09:29

    You can do this using DynamicParam. I saw a decent post on this recently here.

    DynamicParam {
        if ($AuthenticationType -eq 'UsernameAndPassword') {
            #create ParameterAttribute Objects for the username and password
            $unAttribute = New-Object System.Management.Automation.ParameterAttribute
            $unAttribute.Mandatory = $true
            $unAttribute.HelpMessage = "Please enter your username:"
            $pwAttribute = New-Object System.Management.Automation.ParameterAttribute
            $pwAttribute.Mandatory = $true
            $pwAttribute.HelpMessage = "Please enter a password:"
    
            #create an attributecollection object for the attributes we just created.
            $attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]
    
            #add our custom attributes
            $attributeCollection.Add($unAttribute)
            $attributeCollection.Add($pwAttribute)
    
            #add our paramater specifying the attribute collection
            $unParam = New-Object System.Management.Automation.RuntimeDefinedParameter('username', [string], $attributeCollection)
            $pwParam = New-Object System.Management.Automation.RuntimeDefinedParameter('password', [string], $attributeCollection)
    
            #expose the name of our parameter
            $paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
            $paramDictionary.Add('username', $unParam)
            $paramDictionary.Add('password', $pwParam)
            return $paramDictionary
        }
    }
    
    Process {
        $PSBoundParameters.username
        $PSBoundParameters.password
        }
    

提交回复
热议问题