How to Declare Cmdlet Parameters
These examples show how to declare named, positional, required, optional, and switch parameters. These examples also show how to define a parameter alias.
Define a public property as shown in the following code. When you add the Parameter attribute, omit the
Position
keyword from the attribute.C#[Parameter()] public string UserName { get { return userName; } set { userName = value; } } private string userName;
For more information about the Parameter attribute, see Parameter Attribute Declaration.
Define a public property as shown in the following code. When you add the Parameter attribute, set the
Position
keyword to the argument position. A value of 0 indicates the first position.C#[Parameter(Position = 0)] public string UserName { get { return userName; } set { userName = value; } } private string userName;
For more information about the Parameter attribute, see Parameter Attribute Declaration.
Define a public property as shown in the following code. When you add the Parameter attribute, set the
Mandatory
keyword totrue
.C#[Parameter(Position = 0, Mandatory = true)] public string UserName { get { return userName; } set { userName = value; } } private string userName;
For more information about the Parameter attribute, see Parameter Attribute Declaration.
Define a public property as shown in the following code. When you add the Parameter attribute, omit the
Mandatory
keyword.C#[Parameter(Position = 0)] public string UserName { get { return userName; } set { userName = value; } } private string userName;
Define a public property as type System.Management.Automation.SwitchParameter, and then declare the Parameter attribute.
C#[Parameter(Position = 1)] public SwitchParameter GoodBye { get { return goodbye; } set { goodbye = value; } } private bool goodbye;
For more information about the Parameter attribute, see Parameter Attribute Declaration.
Define a public property as shown in the following code. Add an Alias attribute that lists the aliases for the parameter. In this example, three aliases are defined for the same parameter. The first alias provides a shortcut. The second and third aliases provide names you can use for different scenarios.
C#[Alias("UN","Writer","Editor")] [Parameter()] public string UserName { get { return userName; } set { userName = value; } } private string userName;
For more information about the Alias attribute, see Alias Attribute Declaration.
System.Management.Automation.SwitchParameter
PowerShell feedback
PowerShell is an open source project. Select a link to provide feedback: