Creating and Using PowerShell Functions with Input Parameters

PowerShell is a powerful scripting language that enables IT professionals to automate complex systems and manage configurations efficiently. One of the core features of PowerShell is the ability to define functions with input parameters, which enhances script modularity and reusability. This blog post will walk you through how to create a PowerShell function with input parameters, discuss parameter data types, and demonstrate how to call your custom functions.

Defining a Function with Parameters

A function in PowerShell encapsulates a block of code with a specific task. To define a function, you use the function keyword followed by the function’s name and a code block. Input parameters are defined within a param block inside the function. Here’s a basic example:

function Get-Multiplication {
    param (
        [int]$Number1,
        [int]$Number2
    )
    $Product = $Number1 * $Number2
    return $Product
}

Understanding Parameter Data Types

In the Get-Multiplication function, the parameters $Number1 and $Number2 are typed as [int], which means they accept integers. PowerShell supports various data types for parameters to ensure input data is validated. Common data types include:

  • [string]: Textual data
  • [bool]: Boolean (True/False) values
  • [double]: Floating-point numbers
  • [datetime]: Date and time values

Specifying data types is not mandatory but is a good practice to avoid data type errors in your scripts.

Calling Functions with Parameters

After defining your function, you can invoke it by passing values to its parameters. Here’s how to call the Get-Multiplication function with two numbers:

$result = Get-Multiplication -Number1 10 -Number2 20
Write-Output $result

This script will output 200, the product of 10 and 20.

Using Advanced Parameter Attributes

PowerShell also allows for advanced parameter behaviors using attributes, which can define a parameter as mandatory, accept input from the pipeline, or validate input ranges. For example:

function Get-Addition {
    param (
        [Parameter(Mandatory=$true)]
        [int]$Number1,

        [Parameter(Mandatory=$true)]
        [int]$Number2
    )
    return $Number1 + $Number2
}

Setting Default Values for Parameters

You can also set default values for parameters to be used when no value is provided:

function Get-FullName {
    param (
        [string]$FirstName,
        [string]$LastName = 'Doe'
    )
    return "$FirstName $LastName"
}

If Get-FullName is called with only the first name, it will use ‘Doe’ as the last name by default.