How to Create and Use Functions in PowerShell?

Functions are very important in any programming language; the same applies to PowerShell. If you want to write PowerShell scripts, you should know how to create and use functions in PowerShell. I will show you the details here so that PowerShell beginners can also understand.

What is a Function in PowerShell?

A function in PowerShell is a named block of code that performs a specific task. Functions are used to encapsulate code for reuse and better organization. They can take input parameters, process data, and return results. Using functions, you can avoid code duplication and make your scripts more modular and easier to maintain.

Why Use Functions in PowerShell?

Here are a few advantages of using functions in PowerShell.

  1. Code Reusability: Functions allow you to write a piece of code once and reuse it multiple times throughout your script.
  2. Modularity: Breaking down complex scripts into smaller, manageable functions makes your code more organized and easier to read.
  3. Maintainability: Functions make it easier to update and maintain your scripts. If you need to change a specific functionality, you only need to update the function rather than searching through the entire script.
  4. Testing: Functions can be tested independently, which helps identify bugs and ensure that each part of your script works correctly.

Syntax of a PowerShell Function

In PowerShell, functions are defined using the Function keyword followed by a name and a pair of curly braces {}. Inside the braces, you place the code to be executed.

The basic syntax for defining a function in PowerShell is as follows:

Function FunctionName {
    # Your code here
}
  • Function: The keyword used to declare a function.
  • FunctionName: The name you give to your function. It’s good practice to use a verb-noun naming convention (e.g., Get-UserInfo).
  • {}: Curly braces enclose the code block that makes up the function.

Here is a simple example.

Function Say-Hello {
    Write-Output "Hello, World!"
}

The function’s name should use approved verbs like Get, Set, or New, followed by a noun. This helps maintain standard naming conventions and improves code readability.

When defining functions, make sure the name clearly indicates what the function does. This helps other users (or yourself, later) understand the function’s purpose without sifting through the code.

Read PowerShell Data Types

Create and Use functions in PowerShell

Now, let us check out, with examples, how to create and use functions in PowerShell.

Basic PowerShell Function

Let’s start with a simple example. Suppose we want to create a function that greets a user. Here is the complete PowerShell script code:

Function Greet-User {
    Write-Output "Hello, welcome to PowerShell scripting!"
}

# Calling the function
Greet-User

In this example, we defined a Greet-User function that outputs a greeting message. We then call the function by simply typing its name.

After executing the PowerShell script, you can see the output in the screenshot below.

PowerShell functions

PowerShell Functions with Parameters

Functions become even more powerful when they accept parameters. Parameters allow you to pass data into your function, making it more flexible.

Here is the syntax of the PowerShell function with parameters.

Function FunctionName {
    param (
        [Parameter1Type]$Parameter1,
        [Parameter2Type]$Parameter2
    )
    # Your code here
}

Here is an example of a PowerShell function that has Parameters.

Let’s create a function that greets a user by name.

Function Greet-User {
    param (
        [string]$FirstName,
        [string]$LastName
    )
    Write-Output "Hello, $FirstName $LastName! Welcome to PowerShell scripting!"
}

# Calling the function with parameters
Greet-User -FirstName "John" -LastName "Doe"

In this example, the Greet-User function takes two parameters: FirstName and LastName. When calling the function, we provide values for these parameters.

Look at the screenshot below after I executed the PowerShell script using VS code.

Powershell functions with parameters

Read PowerShell Function Examples with Parameters

PowerShell Function Default Parameter Values

You can also set default values for parameters in PowerShell functions. The default value will be used if the caller does not provide a value.

Here is a syntax:

Function Greet-User {
    param (
        [string]$FirstName = "John",
        [string]$LastName = "Doe"
    )
    Write-Output "Hello, $FirstName $LastName! Welcome to PowerShell scripting!"
}

# Calling the function without parameters
Greet-User

In this case, if no parameters are provided, the function will use “John” and “Doe” as default values.

Return Values from A PowerShell Functions

PowerShell Functions can also return values. You can use the return keyword in a PowerShell function to return a value.

Here is an example:

Function Add-Numbers {
    param (
        [int]$Number1,
        [int]$Number2
    )
    return $Number1 + $Number2
}

# Calling the function and storing the result
$result = Add-Numbers -Number1 5 -Number2 10
Write-Output "The sum is: $result"

Here, the Add-Numbers function takes two integers as parameters, adds them, and returns the result.

Mandatory and Optional Parameters in a Function

Parameters in PowerShell functions can be either mandatory or optional. A mandatory parameter must be provided when the function is called; otherwise, PowerShell will prompt the user to enter a value. To define a mandatory parameter, use the Mandatory attribute:

Here is the syntax:

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

Optional parameters, however, do not require user input if no value is specified. They can be assigned a default value:

param (
    [Parameter(Mandatory=$false)]
    [string]$City = "Unknown"
)

This setup ensures the function can run with minimal user input but still forces crucial inputs when needed.

Use Multiple Parameters in a PowerShell Function

You can also create functions that handle multiple parameters and contain more complex logic. Let’s create a function in PowerShell that calculates the total price of items in a shopping cart, including tax.

Function Calculate-TotalPrice {
    param (
        [hashtable]$Cart,
        [decimal]$TaxRate = 0.07
    )
    $total = 0
    foreach ($item in $Cart.Keys) {
        $total += $Cart[$item]
    }
    $totalWithTax = $total * (1 + $TaxRate)
    return [math]::Round($totalWithTax, 2)
}

# Simulated shopping cart
$cart = @{
    "Laptop" = 999.99
    "Mouse"  = 25.50
    "Keyboard" = 45.75
}

# Calling the function
$totalPrice = Calculate-TotalPrice -Cart $cart
Write-Output "The total price including tax is: $totalPrice"

In this example, the Calculate-TotalPrice function takes a hashtable representing a shopping cart and a tax rate as parameters.

Positional and Named Parameters

In PowerShell, function parameters can be positional or named. Positional parameters rely on the order in which arguments are supplied:

function Test-Params {
    param ([string]$First, [string]$Second)
    Write-Output "$First $Second"
}

Test-Params "Hello" "World"

For named parameters, the parameter names are used to match the inputs:

function Test-Params {
    param ([string]$First, [string]$Second)
    Write-Output "$First $Second"
}

Test-Params -First "Hello" -Second "World"

PowerShell Function Parameter Sets

Parameter sets allow you to define different sets of parameters for a function. Here is an example.

Function Get-Info {
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "ByName")]
        [string]$Name,

        [Parameter(Mandatory = $true, ParameterSetName = "ByID")]
        [int]$ID
    )
    switch ($PSCmdlet.ParameterSetName) {
        "ByName" { Write-Output "Getting info by Name: $Name" }
        "ByID" { Write-Output "Getting info by ID: $ID" }
    }
}

# Calling the function with different parameter sets
Get-Info -Name "John Doe"
Get-Info -ID 12345

Pipeline Input as Parameter to Function

PowerShell functions can also accept input from the pipeline. Here is an example.

Function ConvertTo-UpperCase {
    param (
        [Parameter(ValueFromPipeline = $true)]
        [string]$InputString
    )
    process {
        Write-Output $InputString.ToUpper()
    }
}

# Using the function with pipeline input
"john doe", "jane smith" | ConvertTo-UpperCase

In this example, the ConvertTo-UpperCase function accepts input from the pipeline and converts each input string to uppercase.

Begin, Process, and End Blocks in a Function

PowerShell functions can include Begin, Process, and End blocks to manage different execution stages.

  • Begin block: Executes once at the start and is typically used to initialize variables.
  • Process block: Processes each item received from the pipeline, executing for each object.
  • End block: Runs after all pipeline input has been processed, useful for cleanup tasks.

Example:

function Get-Sample {
    [CmdletBinding()]
    param (
        [string]$Name,
        [int]$Age
    )
    begin {
        # Code to initialize
    }
    process {
        # Code to process each item
    }
    end {
        # Code to clean up
    }
}

This is how to use blocks in PowerShell functions.

Read Run PowerShell Script From Command Line With Parameters

Error Handling in Functions in PowerShell

It is always good to handle errors in PowerShell functions. PowerShell provides different methods for error handling, such as try-catch blocks and error variables. Let’s see how to incorporate error handling in functions.

Use Try-Catch

Here is how to use try-catch in PowerShell functions.

Function Divide-Numbers {
    param (
        [int]$Dividend,
        [int]$Divisor
    )
    try {
        if ($Divisor -eq 0) {
            throw "Division by zero is not allowed."
        }
        $result = $Dividend / $Divisor
        return $result
    } catch {
        Write-Output "Error: $_"
    }
}

# Calling the function with error handling
$result = Divide-Numbers -Dividend 10 -Divisor 0
Write-Output "Result: $result"

In this example, the Divide-Numbers function checks if the divisor is zero and throws an error if it is. The try-catch block catches the error and outputs an appropriate message.

Use -ErrorAction and $Error

PowerShell also allows you to control error behavior using -ErrorAction and the $Error automatic variable.

Here is how to use these variables for error handling in a function in PowerShell.

Function Get-FileContent {
    param (
        [string]$FilePath
    )
    Get-Content -Path $FilePath -ErrorAction Stop
}

# Calling the function with error handling
try {
    $content = Get-FileContent -FilePath "nonexistentfile.txt"
    Write-Output $content
} catch {
    Write-Output "Error: $_"
}

Here, the Get-FileContent function uses -ErrorAction Stop to ensure that any errors encountered by Get-Content are treated as terminating errors. The try-catch block then handles these errors.

Read PowerShell Functions: Return Values and Multiple Values

How to Call Functions in PowerShell

To call a function in PowerShell, users must understand the syntax and how to pass parameters effectively. Now, let me show you the basic ways to call functions and how to pass arguments to call functions in PowerShell.

Simple PowerShell Function Call

To call a function in PowerShell, you simply type the function’s name followed by parentheses. For example, given a function named Greet-User, you can call it by typing:

Greet-User

This will execute the code within the Greet-User function.

Pass Parameters to Functions

PowerShell functions often take parameters to make them more flexible. To pass parameters, you include them in the parentheses after the function name. For instance, if Greet-User accepts a parameter for a user’s name:

function Greet-User {
    param ($Name)
    Write-Output "Hello, $Name!"
}

You can call this function and pass a name as follows:

Greet-User -Name "Alice"

This leads to the output: Hello, Alice!. Parameters can be mandatory or optional. Use the param block to define them, ensuring you specify whether they are required or have default values.

For multiple parameters, separate each one with a space like the one below:

Greet-User "Alice" 25

Best Practices for PowerShell Functions

While creating and using functions in PowerShell, you should follow a few best practices.

Naming Conventions and Approved Verbs

Functions should follow a verb-noun format. For example, a function that retrieves processes could be named Get-Process.

PowerShell has a list of approved verbs that should be used to ensure consistency. Some common verbs include Get, Set, Remove, and Start. Using these verbs helps others understand the function’s purpose quickly.

Moreover, function names should be in PascalCase. Capitalize the first letter of each word, such as Start-Service or Stop-Process, to improve readability.

Comment-Based Help and Documentation

Documenting functions with comment-based help enhances their usability. Include remarks describing the function’s purpose, parameters, and outputs.

Begin the documentation with .SYNOPSIS to give a brief description. Use .DESCRIPTION for more details. Documenting the parameters with .PARAMETER helps clarify required inputs. For example:

<#
.SYNOPSIS
   Retrieves the list of running processes.
.DESCRIPTION
   Retrieves and displays the list of all running processes on the system.
.PARAMETER Name
   The name of the process to retrieve.
.EXAMPLE
   Get-Process -Name "notepad"
#>

Including these comments makes it easier for others to understand and use the functions. It also helps with code maintenance and future updates.

PowerShell Functions Examples

Here are a few PowerShell functions examples.

Example 1: Retrieve User Information

The below PowerShell function retrieves user information from a simulated database using a hashtable.

# Simulated database of users
$users = @{
    "john.doe" = @{
        FirstName = "John"
        LastName  = "Doe"
        Email     = "john.doe@example.com"
    }
    "jane.smith" = @{
        FirstName = "Jane"
        LastName  = "Smith"
        Email     = "jane.smith@example.com"
    }
}

Function Get-UserInfo {
    param (
        [string]$Username
    )
    if ($users.ContainsKey($Username)) {
        return $users[$Username]
    } else {
        Write-Output "User not found."
    }
}

# Calling the function
$userInfo = Get-UserInfo -Username "john.doe"
if ($userInfo) {
    Write-Output "First Name: $($userInfo.FirstName)"
    Write-Output "Last Name: $($userInfo.LastName)"
    Write-Output "Email: $($userInfo.Email)"
}

Example 2: Calculate Total Price with Tax

This PowerShell function calculates the total price of items in a shopping cart, including tax.

Function Calculate-TotalPrice {
    param (
        [hashtable]$Cart,
        [decimal]$TaxRate = 0.07
    )
    $total = 0
    foreach ($item in $Cart.Keys) {
        $total += $Cart[$item]
    }
    $totalWithTax = $total * (1 + $TaxRate)
    return [math]::Round($totalWithTax, 2)
}

# Simulated shopping cart
$cart = @{
    "Laptop" = 999.99
    "Mouse"  = 25.50
    "Keyboard" = 45.75
}

# Calling the function
$totalPrice = Calculate-TotalPrice -Cart $cart
Write-Output "The total price including tax is: $totalPrice"

Example 3: Convert Text to Uppercase

The below function in PowerShell converts input text to uppercase and supports pipeline input.

Function ConvertTo-UpperCase {
    param (
        [Parameter(ValueFromPipeline = $true)]
        [string]$InputString
    )
    process {
        Write-Output $InputString.ToUpper()
    }
}

# Using the function with pipeline input
"john doe", "jane smith" | ConvertTo-UpperCase

Here is the output in the screenshot below:

PowerShell Function Examples

Example 4: Check Disk Space

This PowerShell function checks the available disk space on a specified drive and returns a warning if the space is below a certain threshold.

Function Check-DiskSpace {
    param (
        [string]$DriveLetter = "C",
        [int]$ThresholdGB = 10
    )
    $drive = Get-PSDrive -Name $DriveLetter
    $freeSpaceGB = [math]::Round($drive.Free / 1GB, 2)
    if ($freeSpaceGB -lt $ThresholdGB) {
        Write-Output "Warning: Free space on drive $DriveLetter is below $ThresholdGB GB. Current free space: $freeSpaceGB GB."
    } else {
        Write-Output "Drive $DriveLetter has sufficient free space: $freeSpaceGB GB."
    }
}

# Calling the function
Check-DiskSpace -DriveLetter "C" -ThresholdGB 15

Example 5: Backup Files

The below PowerShell function backs up files from a source directory to a destination directory.

Function Backup-Files {
    param (
        [string]$SourceDirectory,
        [string]$DestinationDirectory
    )
    if (-Not (Test-Path $SourceDirectory)) {
        Write-Output "Source directory does not exist."
        return
    }
    if (-Not (Test-Path $DestinationDirectory)) {
        New-Item -ItemType Directory -Path $DestinationDirectory
    }
    Copy-Item -Path "$SourceDirectory\*" -Destination $DestinationDirectory -Recurse -Force
    Write-Output "Backup completed from $SourceDirectory to $DestinationDirectory."
}

# Calling the function
Backup-Files -SourceDirectory "C:\Users\JohnDoe\Documents" -DestinationDirectory "D:\Backup\Documents"

Conclusion

I hope this tutorial gave you a complete idea of how to create and use PowerShell functions. I explained the syntax and a few examples of functions in PowerShell.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.