PowerShell Function Parameters: A Beginner’s Guide

A cornerstone of any programming or scripting language is the concept of functions – reusable blocks of code that perform a specific task. In PowerShell, a function’s effectiveness is amplified by its use of parameters. These little gateways into the function allow us to control its operation flexibly and dynamically. Function parameters allow you to pass values to a function, making it more versatile and customizable. In this article, we’ll cover the basic syntax of function parameters, discuss the different types available through PowerShell, and explore real-world examples demonstrating their power.

An Overview of PowerShell Function Parameters

At a high level, function parameters are simply the inputs that your PowerShell script requires to execute properly. These inputs can be passed to the script as named arguments (e.g., -Parameter “Value”) or through the pipeline. They serve as the primary mode of input into a function, allowing us to pass information and influence the function’s behavior. Imagine a function as a black box that performs a task. Parameters are like dials and switches on this box that you can adjust according to your requirements.

In essence, parameters make your functions versatile and reusable, enabling you to produce more efficient, maintainable, and scalable scripts. Like PowerShell cmdlets, the function parameters extend the usability and flexibility of functions. Let’s dive into the creation and usage of parameters in PowerShell functions.

Creating a PowerShell Function with Parameters

In PowerShell, function parameters are defined in the param block within the function itself. This block can include a variety of parameters, each with its own attributes, like data types, default values, validation logic, and more. You can define one or more parameters, each with a name, data type, validation logic, and optional default value. Creating a parameter in a PowerShell function is straightforward. It just starts with param keyword:

Let’s consider another example:

#Create a function with parameter
function Greet-User {
    param (
        [string]$Name
    )

    Write-host "Hello, $Name!"
}

#Call the function with parameter
Greet-User "Alice"

In this function, we’ve declared a parameter $Name of the type [string]. When calling this function, we can provide a name, like so: Greet-User -Name "Alice". The function will output Hello, Alice!. Please note, the parameter variables are scoped within the function.

Creating functions with multiple parameters in PowerShell

Sometimes, you may need to create functions that accept multiple parameters. PowerShell allows you to define functions with multiple parameters by simply specifying them in the param block. Let’s take a look at an example. Here’s a simple function that takes two integer parameters and returns their sum:

Function Add-Numbers {
Param (
    [int]$num1,
    [int]$num2
)
   $sum = $num1 + $num2
   return $sum
}

In this example, we defined two parameters: $num1 and $num2. The data type for both parameters is [int], meaning they should be integers. You can add Additional parameters in the same way by separating them with a comma.

PowerShell also has an automatic variable $args that contains an array of the parameter values that are passed to a function, script, or script block.

Passing Function Parameters

How do you call a function with parameters in PowerShell? To use a function with parameters, you need to pass values to the function when you call it. You can do this by specifying the parameter names and their values, separated by commas. For example, to use the Add-Numbers function we defined above, you can call it like this:

Add-Numbers -num1 5 -num2 3

This will pass the values 5 and 3 to the $num1 and $num2 parameters, respectively. If you don’t specify a value for $num2, it will use the default value of 0.

PowerShell Function Template with Parameters

You can quickly create a PowerShell function from a template along with parameters using “Snippets”. In PowerShell ISE, You can quickly create a function from the template. Open PowerShell ISE, In the “Edit” menu, click on the “Start Snippets” menu item. This can be a quick starter for creating advanced PowerShell functions with parameter attributes.

<#
.Synopsis
   Short description
.DESCRIPTION
   Long description
.EXAMPLE
   Example of how to use this cmdlet
.EXAMPLE
   Another example of how to use this cmdlet
#>
function Verb-Noun
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Param1,

        # Param2 help description
        [int]
        $Param2
    )

    Begin
    {
    }
    Process
    {
    }
    End
    {
    }
}

Parameter Types

PowerShell supports a variety of parameter types. Besides basic types like [string], [int], and [bool], you can also use more complex types like [array], [hashtable], or even your custom objects. Here’s a summary of the different parameter types that you can use in PowerShell:

  1. [string]: This represents a sequence of characters or text string.
  2. [int]: This stands for integer numbers (whole numbers).
  3. [double]: This represents a number that can have a decimal point (a floating-point number).
  4. [bool]: This represents a Boolean value, either $true or $false.
  5. [array]: This is used for an array of items, which can be of any type.
  6. [string[]]: This represents an array of strings.
  7. [hashtable]: This stands for a hashtable (also known as a dictionary in some other languages), which is a collection of key-value pairs.
  8. [pscustomobject]: This is used for a custom object type.
  9. [DateTime]: This represents a date and time value.

In addition, if you don’t specify a type for your PowerShell parameter, it will be treated as the generic type [object], and PowerShell will try to convert the value to an appropriate type based on how it is used in the function.

Let’s take a look at an example:

function MyFunction {
    param(
        [string]$Name,
        [int]$Age,
        [bool]$IsEnabled
    )
    # Function body
}

In this example, the function MyFunction accepts three parameters: $Name, $Age, and $IsEnabled. When calling the function, you can pass values to these parameters, allowing you to customize its behavior based on your specific requirements. For example, You can quickly create a function to extend an existing PowerShell cmdlet:

function Get-LargerFiles {
  Param($Size)
  Get-ChildItem -Path $HOME -Recurse | Where-Object {
    $_.Length -gt $Size -and !$_.PSIsContainer
  }
}

Get-LargerFiles -Size 10240000

This function gets all files >100MB under the user’s profile.

Parameter set in function parameters

In PowerShell, a parameter set is a group of parameters that function together for a single scenario, and a function can have multiple parameter sets to handle different scenarios. The ParameterSetName property is used to specify which parameter set a particular parameter belongs to. This allows you to have parameters that are only available for certain use cases of your function.

A function can have multiple parameter sets, but only one can be used each time the function is invoked. Let’s consider a function that has two different ways of retrieving user information – either by a user’s name or by their user ID.

Here’s an example of a function with two parameter sets:

function Get-UserInfo {
    [CmdletBinding(DefaultParameterSetName='ByName')]
    param (
        [Parameter(Mandatory=$true, ParameterSetName='ByName')]
        [string]$Name,
        
        [Parameter(Mandatory=$true, ParameterSetName='ByID')]
        [int]$ID
    )

    switch ($PSCmdlet.ParameterSetName) {
        'ByName' { Write-Output "Fetching user information by Name: $Name" }
        'ByID' { Write-Output "Fetching user information by ID: $ID" }
    }
}

This function has two parameter sets – ‘ByName’ and ‘ByID’. When called with a -Name parameter, it fetches user information by name, and when called with -ID, it fetches user information by user ID. To use this function, you would do something like the following:

Get-UserInfo -Name "Alice"
Get-UserInfo -ID 123

The first call will output Fetching user information by Name: Alice, and the second call will output Fetching user information by ID: 123.

Leveraging switch parameters in PowerShell functions

Switch parameters are a special type of parameter in PowerShell that can be used to control the behavior of a function based on a boolean condition. Switch parameters are typically used for binary options, where the function performs a certain action if the switch is enabled, and a different action if it is disabled. Let’s see how to use switch parameters:

function Copy-Files {
    param (
        [Parameter(Mandatory=$true)]
        [string]$SourcePath,

        [Parameter(Mandatory=$true)]
        [string]$DestinationPath,

        [switch]$Overwrite
    )

    if (Test-Path $DestinationPath) {
        if ($Overwrite) {
            Write-Output "Overwriting existing files at $DestinationPath."
            Copy-Item -Path $SourcePath -Destination $DestinationPath -Recurse -Force
        } else {
            Write-Output "Destination path $DestinationPath already exists. Use -Overwrite to force."
        }
    } else {
        Write-Output "Copying files to $DestinationPath."
        Copy-Item -Path $SourcePath -Destination $DestinationPath -Recurse
    }
}

In this function, $SourcePath and $DestinationPath are mandatory string parameters (Required parameters) that specify the source and destination directories for the copy operation. $Overwrite is a switch parameter that indicates whether to overwrite existing files at the destination. If you call this function with the -Overwrite switch, it will overwrite any existing files at the destination:

Copy-Files -SourcePath "C:\source" -DestinationPath "C:\destination" -Overwrite

Using named parameters in PowerShell functions

When calling a PowerShell function, you can pass parameters by name instead of relying on their positional order. This can make your code more readable and less prone to errors, especially when dealing with functions that have multiple parameters. Let’s see how to use named parameters:

Function Get-FullName($FirstName, $MiddleName, $LastName)
{
    $fullName = ''
    if ($firstName) {
        $fullName += $firstName
    }
    if ($middleName) {
        $fullName += " $middleName"
    }
    if ($lastName) {
        $fullName += " $lastName"
    }
    return $fullName.trim()
}

Get-FullName -FirstName "John" -LastName "Doe"
Get-FullName -FirstName "Jane" -MiddleName "Marie" -LastName "Smith"

In this example, the function Get-FullName is called with either two/three named parameters: -FirstName, -MiddleName and -LastName. By explicitly specifying the parameter names, you can provide values in any order, making your code more flexible and easier to understand.

Mandatory and Optional Parameters

By default, parameters are optional. However, PowerShell allows us to specify mandatory parameters by using the [Parameter(Mandatory=$true)] attribute, causing the function to prompt for them if not provided during the function call. Let’s take a look at an example:

function Greet-User {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Name
    )

    Write-Output "Hello, $Name!"
}

In this version of Greet-User, the $Name parameter is mandatory. If we try to call Greet-User without a -Name argument, PowerShell will prompt us for it.

Positional Parameters

By default, PowerShell function parameters are named, but they can also be positional, meaning they can be passed values based on their position in the function call. Here is an example of a function that uses positional parameters to calculate the area of a rectangle:

function CalculateArea {
    param (
        [Parameter(Position=0)]
        [int]$length,

        [Parameter(Position=1)]
        [int]$width
    )
    return $length * $width
}

In this case, $length is the first positional parameter and $width is the second. You can call this function by passing the values in the correct order, without specifying the parameter names:

$area = CalculateArea 5 10

Validating Input Parameters

Validating user input is another important aspect of creating robust, reliable, and error-free PowerShell scripts. You can specify all kinds of validation logic for your function parameters, from simple data type checks to complex regular expressions and validation scripts. PowerShell offers several ways to validate parameters, enforcing checks such as type, range, pattern, or not null or empty.

ValidateNotNullOrEmpty

This ensures the parameter value is not null or an empty string.

function Greet-User {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$Name
    )

    Write-Output "Hello, $Name!"
}

Here, we added a ValidateNotNullOrEmpty attribute to the $Name parameter. Now, if we call Greet-User -Name "" or Greet-User -Name $null, PowerShell will throw an error.

ValidateSet

This restricts the parameter value to a specific set of values. Here is an example of how to use PowerShell function parameters and validation set:

Function Get-ProcessInfo {
    Param(
        [ValidateSet("notepad", "explorer")]
        [string]$ProcessName
    )

    Get-Process $ProcessName
}

In this example, the Get-ProcessInfo function takes one parameter, $ProcessName, which is validated using the [ValidateSet()] attribute. This ensures that the value passed to the parameter is either “notepad” or “explorer”.

ValidateRange

This ensures the parameter value falls within a specific numerical range.

function Grade-Exam {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateRange(0, 100)]
        [double]$Score
    )

    switch ($Score) {
        { $_ -ge 90 } { return "A" }
        { $_ -ge 80 } { return "B" }
        { $_ -ge 70 } { return "C" }
        { $_ -ge 60 } { return "D" }
        default { return "F" }
    }
}
$grade = Grade-Exam -Score 85
#Will Error
$grade = Grade-Exam -Score 105

If you try to call this function with a score outside the 0-100 range, PowerShell will throw an error:

ValidateScript

This allows you to use a custom script for validation.

function IsPrime {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateScript({
            $number = $_
            if ($number -eq 1) { return $false }
            2..([Math]::Sqrt($number)) | foreach { if ($number % $_ -eq 0) { return $false } }
            return $true
        })]
        [int]$Number
    )

    return "$Number is a prime number."
}

ValidatePattern

For example, if you want to ensure that the $Email parameter is always a valid email address, you can set the validation attribute like this:

function Process-UserInfo {
    param (
        [Parameter(Mandatory=$true)]
        [ValidatePattern("^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$")]
        [string]$Email,

        [Parameter(Mandatory=$true)]
        [string]$Name
    )

    Write-Output "Name: $Name"
    Write-Output "Email: $Email"
}

Process-UserInfo -Name "John Doe" -Email "not-an-email" #End up in error
Process-UserInfo -Name "John Doe" -Email "john.doe@example.com"

This validation logic is specified using a regular expression that ensures the input string matches a valid email format. If the user passes an invalid value for this parameter, the script will prompt them to correct the input.

PowerShell Validate Function Parameters

In all these cases, if the parameter validation fails, PowerShell will throw an error, and the function will not be executed. This way, you can catch issues early, before they cause problems in the rest of your function.

Defining Default Values for Parameters

Setting default values for your PowerShell function parameters is a great way to make your script more user-friendly and efficient. When you define a parameter with a default value, you don’t have to specify that value when you call the function. PowerShell will automatically use the default value if no value is specified. You can define default values in the parameter declaration itself, like this:

Function Get-ProcessInfo {
    Param(
        [string]$ProcessName = "notepad"
    )

    Get-Process $ProcessName
}

In this example, the Get-ProcessInfo function takes one parameter, $ProcessName, which has a default value of “notepad”. If you call the function without specifying a value for $ProcessName, PowerShell will use the default value and return information about the Notepad process.

Let’s see another example of how to set default values for function parameters:

function MyFunction {
    param(
        [string]$Name = "John Doe",
        [int]$Age = 30
    )
    # Function body
}

In this example, the function MyFunction has two parameters: $Name and $Age. If the caller does not provide a value for these parameters, the default values of “John Doe” and 30 will be used, respectively. However, if the caller provides a value for these parameters, the provided values will override the default values.

Using Pipeline Input with Function Parameters

PowerShell also allows you to use pipeline input with function parameters, which can make your scripts more flexible and efficient. To do this, you can define a parameter with the [ValueFromPipeline] attribute, which indicates that the function should accept input from the pipeline. For example, here’s a function that takes an array of numbers and returns their sum:

Function Add-Numbers {
Param (
   [Parameter(ValueFromPipeline=$true)]
   [int[]]$numbers
)
   $sum = $numbers | Measure-Object -Sum | Select-Object -ExpandProperty Sum
   return $sum
}

In this example, we defined a single parameter called $numbers, which accepts an array of integers. We also added the [ValueFromPipeline] attribute to indicate that this parameter can accept input from the pipeline. This means that you can pass an array of numbers to this function using pipeline input, like this:

1, 2, 3, 4, 5 | Add-Numbers

This will pass the array of numbers to the $numbers parameter, and the function will return their sum.

#PowerShell Function with Parameter from Pipeline
Function Test-Pipeline {
  param (
    [Parameter(ValueFromPipeline)]
    $Param
  )
  process { "$($Param.Name) was passed through the pipeline" }
}

#Call the function by passing parameters through Pipeline
Get-Process | Test-Pipeline

This will pass an object representing each running process to the Test-Pipeline function, which will output a message for each one.

Array as Function Parameter in PowerShell

Using arrays as parameters to PowerShell functions allows you to pass multiple values to a parameter. This can be useful when you need to perform the same task on multiple items, such as processing multiple files or folders.

Here is an example of how to use a PowerShell parameter array:

Function Get-File {
    Param(
        [Parameter(Mandatory=$true)]
        [string[]]$Path
    )

    ForEach ($Item in $Path) {
        Get-Item $Item
    }
}
#Call the function
Get-File -Path "C:\Temp\AppLog.txt", "C:\Temp\FolderList.csv"

In this example, the Get-File function takes an array of strings as a parameter, which represents the file or folder path. The function uses a foreach loop to process each item in the array and returns the item using the Get-Item cmdlet.

PowerShell Function Param

Let’s look at an example that uses an array:

function Show-Names {
    param (
        [string[]]$Names
    )

    foreach ($Name in $Names) {
        Write-Output "Hello, $Name!"
    }
}

In this function, $Names is an array of strings. We can pass multiple names like so: Show-Names -Names "Alice", "Bob", "Charlie".

Best practices for using PowerShell parameters

When working with PowerShell function parameters, there are some best practices that you should follow to ensure that your scripts are easy to read, maintain, and debug. Here are some tips:

  • Use descriptive parameter names that explain what the parameter does.
  • Use the [Parameter()] attribute to specify additional properties, such as whether the parameter is mandatory or whether it accepts pipeline input.
  • Use default values for optional parameters.
  • Use named parameters instead of positional parameters, especially when there are many parameters involved.
  • Use validation to ensure that the values passed to the parameters are of the correct type.
  • Provide clear documentation for your functions, including information about the parameters they accept and their expected behavior.

By following these best practices, you can create PowerShell functions with parameters that are easy to use and maintain.

Wrapping up

Mastering function parameters is a crucial step in your journey with PowerShell. They allow you to write advanced functions that are robust, versatile, and adaptable to various scenarios. In this comprehensive guide, we explored the world of function parameters in PowerShell. We learned about the basics of function parameters, the different parameter types available, and how to set default values for parameters. We also saw how to make parameters mandatory, use named parameters, validate input values, work with parameters from the pipeline, and leverage switch parameters. Additionally, we looked at examples of function parameters in PowerShell and discussed best practices for using them effectively.

By understanding and effectively using parameters in your functions, you’ll be able to write more flexible, reusable, and efficient scripts, thereby amplifying your PowerShell prowess. Happy scripting!

What are function parameters in PowerShell?

Function parameters are like inputs you give a function to control its behavior and customize its output. Imagine a function as a machine, and parameters are the knobs and levers you use to adjust its operation.

What are the different types of parameters?

Positional: Parameters used in a specific order without names. Simple and easy to use, but order matters!
Named: Parameters explicitly named when calling the function. More readable and flexible, but remembering names can be challenging.
Switch: Parameters used like flags, either present or absent, often indicating true/false options. Convenient for toggling features.
Dynamic: Parameters that appear depending on other parameters or conditions, offering increased flexibility and data-driven functionality.

How can I document my function parameters?

Use comment-based XML inside your function definition (<# and #>) to provide descriptions, examples, and details about each parameter. This helps users understand how to use your function effectively.

What are parameter sets?

Groups of related parameters used together for specific scenarios. Imagine having different toolkits for different tasks. They help ensure only relevant parameters are available for each use case.

How do I pass values to a function?

Positional: Enter values after the function name in the order defined.
Named: Specify the parameter name followed by the colon and the value (e.g., -ParameterName Value).
Switch: Just include the parameter name without a colon or value to activate it.
Pipeline: Send objects directly to the function using the pipe symbol (|).

Can I specify the type of a PowerShell function parameter?

Yes, you can specify the parameter type by preceding the parameter name with the type. Specifying the type ensures that only values of that type can be passed to the function. For example:
function Get-UserData {
param (
[string]$Name,
[int]$Age
)
# Function body goes here
}

What are mandatory parameters and how do I define them?

Mandatory parameters are parameters that must be provided a value when the function is called. You define a parameter as mandatory by using the [Parameter()] attribute with the Mandatory=$true argument. For example:
function Get-UserName {
param (
[Parameter(Mandatory=$true)]
[string]$Name
)
# Function body goes here
}

How can I define default values for parameters?

Default values for parameters can be defined by assigning a value to the parameter in the function declaration. If the caller does not provide a value for that parameter, the default value is used. For example:
function Get-Data {
param (
[string]$Name = "Default Name",
[int]$Age = 25
)
# Function body goes here
}

Can PowerShell functions accept an array as a parameter?

Yes, PowerShell functions can accept arrays as parameters. You can specify that a parameter accepts an array by typing the parameter as an array, such as [string[]]$Names for an array of strings. For example:
function Get-UserNames {
param (
[string[]]$Names
)
# Function body goes here
Write-host $Names.Count
}
Call Function with array as parameter
Get-UserNames "Thomas","Sam", "Ben"

What is a switch parameter in PowerShell?

Switch parameters are parameters that convey a Boolean true-or-false value through their presence or absence. They do not require a value when called.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *