The Parameter attribute

The Parameter attribute is an optional attribute that is used to define the behavior of a parameter within a script or function. Creating an instance of the Parameter object shows the different properties that might be set:

PS> [Parameter]::new()

Position : -2147483648

ParameterSetName : __AllParameterSets
Mandatory : False
ValueFromPipeline : False
ValueFromPipelineByPropertyName : False
ValueFromRemainingArguments : False
HelpMessage :
HelpMessageBaseName :
HelpMessageResourceId :
DontShow : False
TypeId : System.Management.Automation.ParameterAttribute

A few of these properties should be ignored as they are not intended to be set directly, such as HelpMessageBaseNameHelpMessageResourceId, and TypeId.

A number of the more complex properties are explored in other sections in this chapter, such as ParameterSetNameValueFromPipeline, and ValueFromPipelineByPropertyName.

The Parameter attribute is placed before the parameter itself. The following example shows the simplest use of the Parameter attribute:

[CmdletBinding()]
param (
[Parameter()]
$Paramter1
)

Using the Parameter attribute has the side-effect of turning a basic function into an advanced function, even when the CmdletBinding attribute itself is missing. Get-Command may be used to explore whether CmdletBinding is present:

PS> function Test-CmdletBinding {
>> param (
>> [Parameter()]
>> $Parameter1
>> )
>> }
PS> Get-Command Test-CmdletBinding | Select-Object CmdletBinding

CmdletBinding
-------------
True

This means that the common parameters, including Verbose and ErrorAction, are available to any function that uses the Parameter attribute (for any parameter).

Starting with PowerShell 3, Boolean properties, such as Mandatory and ValueFromPipeline, may be written without providing an explicit argument. For example, Parameter1 is made mandatory in the following code:

function Test-Mandatory {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
$Parameter1
)
}
Use of Mandatory = $false

The default value for Mandatory is false; setting an explicit value of a default provides no benefit and may be counterproductive.

Mandatory is significant and stands out, but the value assigned is less significant and, when reading rapidly, it might be assumed to be true simply because the property is present.
..................Content has been hidden....................

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