Conditional parameters

One possible use of dynamic parameters is to change validation based on the value supplied for another parameter. Another use is to change which parameters are available, again based on the value of another parameter.

The following example changes validValues into ValidateSet depending on the value supplied for the Type parameter:

using namespace System.Management.Automation

function Test-DynamicParam {
[CmdletBinding()]
param (
[Parameter(Mandatory, Position = 1)]
[ValidateSet('Service', 'Process')]
[String]$Type,

[Parameter(Mandatory, Position = 3)]
[String]$Name
)

dynamicparam {
$paramDictionary = [RuntimeDefinedParameterDictionary]::new()

[String[]]$validValues = switch ($Type) {
'Service' { 'Get', 'Start', 'Stop', 'Restart' }
'Process' { 'Get', 'Kill' }
}
$parameter = [RuntimeDefinedParameter]::new('Action', [String], [Attribute[]]@(
[Parameter]@{ Mandatory = $true; Position = 2 }
[ValidateSet]::new($validValues)
)
)
$paramDictionary.Add($parameter.Name, $parameter)

$paramDictionary
}
}

Changing validation in this manner is entirely reliant on the user having typed a value for the Type parameter prior to attempting to use ActionOther comparisons can be made in dynamic parameter blocks, for example a parameter might only appear when a certain condition is met. RuntimeDefinedParameterDictionary is valid even if it is empty and no extra parameters need to be added.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.252