• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Think PowerShell

Think PowerShell

PowerShell for IT Pros

  • About
    • Who I Am
    • Why I Blog
    • Privacy Policy
  • Resources
    • More PowerShell Sites
    • Post Series Index
  • Get Help
  • Show Search
Hide Search

Mastering PowerShell functions

Aaron Rothstein · July 18, 2023 · Leave a Comment

Functions in PowerShell are a fundamental element for creating reusable code. They not only contribute to cleaner and more readable scripts, but they also help reduce redundancy. In this guide, we will dive deep into creating and using functions in PowerShell.

Understanding PowerShell functions

PowerShell functions are named blocks of script that can be used and reused. They are designed to carry out a specific task and can optionally return a value.

A simple function might look like this:

function Show-Message {
    Write-Output "Hello, PowerShell!"
}

To call the function, simply use its name:

Show-Message

Using parameters in functions

Parameters make your functions flexible. They allow you to pass values into your function when you call it.

Here’s a function that accepts a parameter:

function Show-CustomMessage {
    param($message)
    Write-Output $message
}

And you can call it like this:

Show-CustomMessage "Hello, PowerShell!"

Parameter validation

Parameter validation attributes can be used to control the values that a function will accept. This makes your functions more robust.

Here’s a function with a parameter that must have a value (i.e., it cannot be null or empty):

function Show-CustomMessage {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$message
    )

    Write-Output $message
}

Returning values

A function in PowerShell can return a value that can be used elsewhere in your script. You can use the return keyword, but it’s often unnecessary as a function will automatically output any value not assigned to a variable or consumed by a cmdlet.

function Get-Double {
    param([double]$number)
    $double = $number * 2
    return $double
}

Call the function and use its result:

$result = Get-Double -number 2.5
Write-Output $result  # Outputs 5

Advanced functions and cmdlet binding

Cmdlet binding allows your functions to act like compiled cmdlets, giving you access to common parameters like -Verbose, -WhatIf, and -Confirm. You can also define advanced parameters, like pipeline input and parameter sets.

[CmdletBinding()]
function Test-AdvancedFunction {
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string[]]$message
    )

    process {
        foreach ($msg in $message) {
            Write-Verbose "Processing message: $msg"
            Write-Output $msg
        }
    }
}

You can call this advanced function like this:

"Hello", "PowerShell" | Test-AdvancedFunction -Verbose

Best practices

  • Use meaningful names: Name your functions with a Verb-Noun pattern. This aligns with PowerShell cmdlets and ensures readability.
  • Add comment-based help: Adding a help message is essential for others to understand your function’s usage, parameters, and return values.
  • Error handling: Implement try/catch blocks in your functions to handle potential errors gracefully.

Conclusion

Functions are a powerful feature of PowerShell that can greatly enhance the modularity and readability of your scripts. By understanding how to effectively use functions, you can write more robust and reusable PowerShell scripts.

More resources

  • PowerShell 101 – Chapter 9 – Functions | learn.microsoft.com

General

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

Aaron

Think PowerShell

Copyright © 2025 · Monochrome Pro on Genesis Framework · WordPress · Log in