PowerShell Functions [Create and Use Functions]

PowerShell functions are essential building blocks that help simplify scripts and make code more reusable. These blocks of code perform specific tasks when called by name, saving time and reducing repetition in PowerShell scripts. Functions work like mini-programs within your larger script, accepting inputs, processing data, and returning results.

In this tutorial, I will explain how to work with PowerShell functions with examples.

What is a PowerShell Function?

A PowerShell function is a named block of code that performs a specific task. When you create a function, you can call it multiple times within your script without having to rewrite the same code repeatedly.

Here’s a simple example of a PowerShell function:

function Get-USTimeZone {
    Get-TimeZone -ListAvailable | Where-Object {$_.Id -like "*US*"}
}

This function retrieves all time zones that contain “US” in their ID, which is much more convenient than typing the whole command each time you need this information.

PowerShell Functions can accept inputs (parameters) and return outputs. They can be as simple as the example above or much more complex with multiple parameters and advanced logic.

The primary purpose of functions is to create reusable code. Instead of writing the same code multiple times, you can write it once as a function and call it whenever needed.

Function Declaration and Syntax

The basic structure of a PowerShell function begins with the function keyword followed by the function name and a script block enclosed in curly braces {}. Here’s the standard syntax:

function Verb-Noun {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$ParameterName
    )
    
    # Function code goes here
}

The param block defines inputs your function accepts. Parameters can be made mandatory or optional, and you can specify data types like [string] or [int].

PowerShell functions generate errors if required parameters are null, empty strings, or empty arrays.

Now, I will show you how to create a function in PowerShell starting from basic methods.

Check out Pass Objects to Functions in PowerShell

Create PowerShell Functions

Let me show you various methods of creating PowerShell functions.

Method 1: Simple Function Definition

The most basic way to create a function is using the function keyword followed by the function name and code block. Here is an example.

function Backup-UserDocuments {
    $sourceFolder = "C:\Users\$env:USERNAME\Documents"
    $destinationFolder = "D:\Backups\Documents"
    
    if (!(Test-Path $destinationFolder)) {
        New-Item -ItemType Directory -Path $destinationFolder -Force
    }
    
    Copy-Item -Path "$sourceFolder\*" -Destination $destinationFolder -Recurse -Force
    Write-Host "Backup completed successfully!" -ForegroundColor Green
}

To call this PowerShell function, simply type its name:

Backup-UserDocuments

Check out PowerShell Function Return Values

Method 2: Functions with Parameters

Parameters make your functions more flexible by allowing you to pass different values each time you call them. Here is an example of creating a PowerShell function with parameters.

function Convert-FahrenheitToCelsius {
    param (
        [Parameter(Mandatory=$true)]
        [double]$Fahrenheit
    )
    
    $celsius = ($Fahrenheit - 32) * 5/9
    return [Math]::Round($celsius, 2)
}

Now you can call this function with different temperature values:

Convert-FahrenheitToCelsius -Fahrenheit 98.6
# Output: 37

You can see the exact output in the screenshot below:

powershell function

Check out Exit a Function Without Stopping the Script in PowerShell

Method 3: PowerShell Functions with Parameter Validation

For more robust PowerShell functions, you can add parameter validation to ensure the input meets your requirements. Here is an example.

function Get-USStateInfo {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [ValidateSet("Alabama", "Alaska", "Arizona", "Arkansas", "California")]
        [string]$StateName,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet("Capital", "Population", "Abbreviation")]
        [string]$InfoType = "Capital"
    )
    
    $stateData = @{
        Alabama = @{Capital = "Montgomery"; Population = "4.9 million"; Abbreviation = "AL"}
        Alaska = @{Capital = "Juneau"; Population = "0.7 million"; Abbreviation = "AK"}
        Arizona = @{Capital = "Phoenix"; Population = "7.3 million"; Abbreviation = "AZ"}
        Arkansas = @{Capital = "Little Rock"; Population = "3.0 million"; Abbreviation = "AR"}
        California = @{Capital = "Sacramento"; Population = "39.5 million"; Abbreviation = "CA"}
    }
    
    return $stateData[$StateName][$InfoType]
}

You can call this function like:

Get-USStateInfo -StateName "California" -InfoType "Population"
# Output: 39.5 million

Here is the exact output in the screenshot below:

powershell functions

Check out PowerShell Function Array Parameters

Method 4: Functions with Pipeline Support

PowerShell’s pipeline is a powerful feature, and your functions can support it too. Here is an example.

function Test-ServerConnection {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string[]]$ComputerName
    )
    
    process {
        foreach ($computer in $ComputerName) {
            $result = Test-Connection -ComputerName $computer -Count 1 -Quiet
            
            [PSCustomObject]@{
                Server = $computer
                Online = $result
                Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            }
        }
    }
}

Now you can pipe server names to your function:

"server01", "server02", "server03" | Test-ServerConnectio

Or even:

Get-Content C:\servers.txt | Test-ServerConnection

Check out Call Function in If Statement in PowerShell

PowerShell Function Scopes and Modules

Method 5: Control Function Scope

PowerShell functions have different scopes that determine their visibility:

# Global scope function (available everywhere)
function global:Get-GlobalWeather {
    param ([string]$City = "New York")
    # Function implementation
}

# Script scope function (available only in the current script)
function script:Get-ScriptConfig {
    # Function implementation
}

# Local scope function (default, available only in the current scope)
function Get-LocalData {
    # Function implementation
}

Method 6: Create Reusable Function Modules

For functions you use frequently, consider creating a module:

# Save this in a file named USUtilities.psm1
function Get-USHolidays {
    param (
        [int]$Year = (Get-Date).Year
    )
    
    $holidays = @(
        [PSCustomObject]@{Name = "New Year's Day"; Date = Get-Date -Year $Year -Month 1 -Day 1}
        [PSCustomObject]@{Name = "Independence Day"; Date = Get-Date -Year $Year -Month 7 -Day 4}
        [PSCustomObject]@{Name = "Thanksgiving"; Date = Get-Date -Year $Year -Month 11 -Day ((4 - (Get-Date -Year $Year -Month 11 -Day 1).DayOfWeek.value__) % 7 + 22)}
        [PSCustomObject]@{Name = "Christmas Day"; Date = Get-Date -Year $Year -Month 12 -Day 25}
    )
    
    return $holidays
}

Export-ModuleMember -Function Get-USHolidays

You can import and use this module:

Import-Module .\USUtilities.psm1
Get-USHolidays -Year 2025

Check out Get Current Function Name in PowerShell

Error Handling and Debugging in a PowerShell Function

When writing PowerShell functions, properly handling errors and implementing debugging techniques are essential for creating reliable, maintainable code. Effective error handling prevents script failures and provides meaningful feedback to users or calling scripts.

PowerShell functions should implement proper error handling to ensure robustness. The most common approach is using Try-Catch-Finally blocks.

function Get-FileContent {
    param ([string]$Path)
    
    try {
        $content = Get-Content -Path $Path -ErrorAction Stop
        return $content
    }
    catch {
        Write-Error "Failed to read file: $_"
    }
    finally {
        Write-Verbose "File operation completed"
    }
}

The -ErrorAction parameter controls how errors are processed. Setting it to Stop converts non-terminating errors into terminating ones that can be caught.

Best practices include returning meaningful error messages and documenting possible exceptions your function might throw. This helps other developers understand how to handle errors when using your functions properly.

PowerShell Function Best Practices

Now, let me show you some best practices for PowerShell functions.

  1. Use Verb-Noun naming convention – Follow PowerShell’s standard naming pattern (Get-Item, Set-Location, etc.)
  2. Add comment-based help – Document your functions for yourself and others:
function Convert-USGallonsToLiters {
    <#
    .SYNOPSIS
        Converts US gallons to liters.
    
    .DESCRIPTION
        Converts a given value in US gallons to liters using the conversion factor 1 gallon = 3.78541 liters.
    
    .PARAMETER Gallons
        The amount of US gallons to convert.
    
    .EXAMPLE
        Convert-USGallonsToLiters -Gallons 10
        Returns: 37.85
    #>
    
    param (
        [Parameter(Mandatory=$true)]
        [double]$Gallons
    )
    
    return [Math]::Round($Gallons * 3.78541, 2)
}
  1. Return meaningful output – Use appropriate return types, preferably objects over text.
  2. Handle errors gracefully – Use try/catch blocks and meaningful error messages:
function Get-USStockPrice {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Symbol
    )
    
    try {
        $apiUrl = "https://api.example.com/stocks/$Symbol"
        $response = Invoke-RestMethod -Uri $apiUrl -ErrorAction Stop
        return $response.price
    }
    catch {
        Write-Error "Failed to retrieve stock price for $Symbol. Error: $_"
    }
}

In this tutorial, I have explained how to work with functions in PowerShell. You also learned how to create functions in PowerShell with a few examples. Here, I have also shared the best practices you can follow while working with PowerShell functions.

You may also like:

Leave a Comment

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App