Creating a RuntimeDefinedParameter object

A RuntimeDefinedParameter object describes a single parameter. The definition includes the name of the parameter, the parameter type, and any attributes that should be set for that parameter. PowerShell does not include type accelerators for creating RuntimeDefinedParameter; the full name, System.Management.Automation.RuntimeDefinedParametermust be used. The constructor for RuntimeDefinedParameter expects three arguments: a string, which will be the parameter name, a .NET type for the parameter, and a collection or array of attributes that should be assigned. The attribute collection must contain at least one Parameter attribute.

The following example, which creates a parameter named Action, makes use of a using namespace statement to shorten the .NET type names:

using namespace System.Management.Automation
$parameter = [RuntimeDefinedParameter]::new('Action', [String], [Attribute[]]@(
[Parameter]@{ Mandatory = $true; Position = 1 }

[ValidateSet]::new('Start', 'Stop', 'Create', 'Delete')
)
)

The previous parameter is the equivalent of using the following in the param block:

param (
[Parameter(Mandatory, Position = 1)]
[ValidateSet('Start', 'Stop', 'Create', 'Delete')]
[String]$Action
)

As the attributes are not being placed directly above a variable, each must be created as an independent object instance:

  • The shorthand used for the Parameter attribute in the param block cannot be used; Boolean values must be written in full
  • The ValidateSet attribute, and other validation attributes, must also be created as a new object rather than using the attribute syntax

The Parameter attribute declaration takes advantage of PowerShell's ability to assign property values to an object using a hashtable. This is feasible because a Parameter attribute can be created without supplying any arguments, that is, [Parameter]::new() can be used to create a Parameter attribute with default values. This technique cannot be used for the validation attributes, as each requires one or more arguments, therefore ::new or New-Object must be used.

As with a normal parameter, RuntimeDefinedParameter can declare more than one parameter attribute. Each Parameter attribute is added to the attribute collection:

using namespace System.Management.Automation
$parameter = [RuntimeDefinedParameter]::new('Action', [String], [Attribute[]]@(
[Parameter]@{ Mandatory = $true; Position = 1; ParameterSetName = 'First' }

[Parameter]@{ ParameterSetName = 'Second' }
)
)

Any number of parameters might be created in this manner. Each parameter must have a unique name. Each parameter must be added to a RuntimeDefinedParameterDictionary.

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

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