top of page

PowerShell Parameters

PowerShell parameters are used to pass arguments to functions, scripts, or cmdlets, allowing for flexible and reusable code. Here’s a comprehensive guide on PowerShell parameters, including how to define, use, and manage them.

Defining Parameters

Parameters in PowerShell functions or scripts are defined using the param block or the [Parameter()] attribute within the function definition.

Using the param Block

The param block is placed at the beginning of the script or function and is used to define the parameters.

function Get-Sample {
    param (
        [string]$Name,
        [int]$Age
    )
    Write-Output "Name: $Name, Age: $Age"
}

Get-Sample -Name "John" -Age 30
 

Woman Studying

Using the [Parameter()] Attribute

The [Parameter()] attribute allows for more detailed parameter configurations, such as making a parameter mandatory or setting a default value.

function Get-Sample {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Name,

        [Parameter(Mandatory=$false)]
        [int]$Age = 25
    )
    Write-Output "Name: $Name, Age: $Age"
}

Get-Sample -Name "John"
 

Parameter Attributes

PowerShell provides several attributes to control the behavior of parameters.

  • Mandatory: Specifies that the parameter is required.

  • DefaultValue: Sets a default value for the parameter.

  • Position: Defines the position of the parameter when calling the function without named parameters.

  • ValueFromPipeline: Indicates that the parameter can accept values from the pipeline.

  • ValueFromPipelineByPropertyName: Accepts values from the pipeline based on the property name.

function Get-UserInfo {
    param (
        [Parameter(Mandatory=$true, Position=0)]
        [string]$Username,

        [Parameter(Position=1, ValueFromPipeline=$true)]
        [string]$Email
    )
    process {
        Write-Output "Username: $Username, Email: $Email"
    }
}

"john@example.com" | Get-UserInfo -Username "John"
 

PowerShell Using Parameter
bottom of page