Dynamic parameters

Dynamic parameters allow a developer to define the behavior of parameters when a function is run, rather than hardcoding that behavior in advance in a param block. Dynamic parameters can be used to overcome some of the limitations inherent in a param block. For example, it is possible to change the parameters presented by a command based on the value of another parameter. It is also possible to dynamically write validation, such as dynamically assigning a value for the ValidateSet attribute.

Dynamic parameters remain unpopular in the PowerShell community. They are relatively complex; that is, they are hard to define, and difficult to troubleshoot as they tend to silently fail rather than raising an error. Dynamic parameters have a named block: dynamicparam. If dynamicparam is used, the default blocks for a script or function cannot be used; all code must be contained within explicitly declared named blocks. The CmdletBinding attribute must be explicitly declared when using dynamicparam, parameters will not be created without CmdletBinding, nor will an error message be shown to explain that.

The following example includes an empty dynamicparam block as well as an end block, which would have been implicit if dynamicparam were not present:

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

dynamicparam { }
end {
Write-Host 'Function body'
}
}

If the end block declaration is missing, a syntax error will be displayed. This is shown as follows, it does not state that the problem is the dynamicparam block, or because of a missing named block:

PS> function Test-DynamicParam {
>> [CmdletBinding()]

>> param ( )
>> dynamicparam { }
>> Write-Host 'Function body'
>> }
At line:1 char:28
+ function Test-DynamicParam {
+ ~
Missing closing '}' in statement block or type definition.
At line:4 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndCurlyBrace

The dynamicparam block must output a RuntimeDefinedParameterDictionary object. The dictionary should contain one or more RuntimeDefinedParameter objects.

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

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