Param - PowerShell


Overview

Param is a PowerShell command used to create parameters for functions and scripts. It allows you to define the input and output types, set default values, and specify other parameters to control the behavior of your code.

Syntax

Param
{
    [Parameter(Mandatory=$true, Position=0)]
    [type] $parameterName1

    [Parameter(Mandatory=$false)]
    [type] $parameterName2

    ...
}

Options/Flags

  • Mandatory: Specifies whether the parameter is required. Default is $false.
  • ParameterSetName: Specifies the parameter set to which the parameter belongs. Default is the default parameter set.
  • Position: Specifies the position of the parameter in the parameter list. Default is 0.
  • ValueFromPipeline: Specifies whether the parameter can receive values from the pipeline. Default is $false.
  • ValueFromPipelineByPropertyName: Specifies whether the parameter can receive values from the pipeline by property name. Default is $false.
  • HelpMessage: Specifies the help message for the parameter.

Examples

Simple Parameter Definition

Param([int]$age)

Parameter with Default Value

Param([int]$age = 25)

Parameter with Multiple Attributes

Param([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [int]$age)

Complex Example

Param
{
    [Parameter(Mandatory=$true)]
    [string]$name

    [Parameter(Mandatory=$false)]
    [ValidateScript({ $_ -gt 0 })]
    [int]$age

    [Parameter(ParameterSetName="Verbose")]
    [switch]$Verbose
}

Common Issues

  • Ambiguous parameters: When multiple parameters match a given input, PowerShell may not be able to determine the intended parameter. Use the FullyQualifiedName parameter to specify the exact parameter name.
  • Incorrect data types: If a parameter expects a specific data type and it receives a different type, PowerShell will throw an error. Ensure that the input values match the expected data types.
  • Missing required parameters: If a parameter is marked as Mandatory and no value is provided, PowerShell will throw an error. Always specify required parameters.

Integration

Param can be combined with other PowerShell commands to create powerful scripts. For example:

  • Get-Command: To retrieve a list of available commands and their parameters.
  • ConvertTo-Json: To convert parameter values to JSON format.
  • Invoke-Command: To run commands remotely and specify parameters.