Using dynamic parameters

Dynamic parameters must be accessed using the PSBoundParameters variable within a function or script; dynamic parameters do not initialize variables of their own.

The value of the Action parameter used in the previous examples must be retrieved by using Action as a key, shown as follows:

using namespace System.Management.Automation

function Test-DynamicParam {
[CmdletBinding()]
param ( )

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

$parameter = [RuntimeDefinedParameter]::new('Action', [String], [Attribute[]]@(
[Parameter]@{ Mandatory = $true; Position = 1 }

[ValidateSet]::new('Start', 'Stop', 'Create', 'Delete')
)
)
$paramDictionary.Add($parameter.Name, $parameter)

$paramDictionary
}

end {
Write-Host $psboundparameters['Action']
}
}

As with parameters from the param block, the $psboundparameters.ContainsKey method may be used to find out whether a user has specified a value for the parameter. Dynamic parameters cannot have a default value; any default values must be created in begin, process, or end.

A dynamic parameter that accepts pipeline input, like a normal parameter that accepts pipeline input, will only have a value within the process and end blocks. The end block will only see the last value in the pipeline. The following example demonstrates this:

using namespace System.Management.Automation

function Test-DynamicParam {
[CmdletBinding()]
param ( )

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

$parameter = [RuntimeDefinedParameter]::new('InputObject', [String], [Attribute[]]@(
[Parameter]@{ Mandatory = $true; ValueFromPipeline = $true }
)
)
$paramDictionary.Add($parameter.Name, $parameter)

$paramDictionary
}

begin {
'BEGIN: Input object is present: {0}' -f @(
$psboundparameters.ContainsKey('InputObject')
)
}

process {
'PROCESS: Input object is present: {0}; Value: {1}' -f @(
$psboundparameters.ContainsKey('InputObject')
$psboundparameters['InputObject']
)
}

end {
'END: Input object is present: {0}; Value: {1}' -f @(
$psboundparameters.ContainsKey('InputObject')
$psboundparameters['InputObject']
)
}
}

The function can be used with arbitrary input values, for example:

PS> 1..2 | Test-DynamicParam
BEGIN: Input object is present: False
PROCESS: Input object is present: True; Value: 1
PROCESS: Input object is present: True; Value: 2
END: Input object is present: True; Value: 2

The PSBoundParameters variable, and any other parameters, may be referenced inside the dynamicparam block.

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

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