business.com receives compensation from some of the companies listed on this page. Advertising Disclosure
BDC Hamburger Icon

MENU

Close
BDC Logo
Search Icon
Updated Nov 02, 2023

Understanding Functions in PowerShell

author image
Adam Bertram, Senior Writer & Expert on Business Operations

Table of Contents

Open row

When you first start writing scripts, you may not necessarily be focused on modularity, reusability and best practice. However, as the code you write gets more complex, it becomes increasingly beneficial to create repeating elements. You can avoid duplicating code by creating PowerShell functions instead. This approach saves you a lot of time because you don’t have to copy and paste the same code time and time again.

These small “building blocks” of code are PowerShell functions. In this article, we’ll cover some basic PowerShell functions as well as more advanced examples. 

What are functions in PowerShell?

A function in PowerShell is a grouping of code that has an optional input and output. It’s a way of collecting a bunch of code to perform one or many times by just pointing to it instead of duplicating that code repeatedly. For example, you can build functions to perform tasks such as syncing folders or managing IIS application pools.

Below, you’ll find examples of basic functions and more advanced functions.

TipBottom line

You don’t have to write full scripts to take advantage of PowerShell functions. For quick tasks or testing, define them directly in the console. This allows you to do quick prototyping or run ad hoc tasks without quitting your console session. This approach is particularly handy when you are trying to manage file system ACLs or remotely invoke applications.

Basic functions

There are two kinds of functions in PowerShell: basic and advanced. As the term implies, basic functions are the simplest functions that can be created; they don’t have the fancy built-in capabilities of advanced functions. They are created or declared by using the function statement followed by a set of curly braces:

function Do-Something {}

The above example is technically a function that can then be called by invoking Do-Something, but in its current form, it doesn’t do very much. This is because we haven’t included any code inside to run. Let’s add some simple code inside so that it actually does something. For example, you can use the Write-Host command that writes text to the PowerShell console:

function Do-Something {

    Write-Host ‘I did something!’

}

You can then invoke this function using the following:

PS > Do-Something

I did something!

As you can see, when invoked, it runs the code inside the function. What if you’d like to pass something into the code inside the function when it’s running? You can create one or more parameters inside a parameter block:

function Do-Something {

param( $String )

Write-Host “I did something — $String!”}

To call this function with a parameter, use this:

PS > Do-Something -String ‘thing’

I did something — thing!

Notice that you specified the String parameter by adding a dash, followed by the parameter name, followed by the value right after you called Do-Something. These are the basics of passing parameters to functions.

Bottom LineBottom line

Understanding how to use parameters in functions allows you to write flexible, adaptable scripts that can handle a variety of situations. You can then make minor changes to the scripts as your needs change.

Advanced functions

Basic functions work, but most of the time, you’ll find yourself creating advanced functions. Advanced functions are functions that include all of the functionality as basic functions but also come with some built-in features that basic functions lack. 

For example, PowerShell has a concept of streams called Error, Warning, Verbose, etc. These streams are critical in correctly displaying output to users. Basic functions do not inherently understand these streams.

Let’s say you want to display an error message if something happens inside the function. However, you also want the ability to hide this error message at certain times. With a basic function, it would be cumbersome to do this. However, with an advanced function, that functionality is built in. 

Advanced functions, by default, already have parameters even if you don’t include them — for example, Verbose, ErrorAction, WarningVariable and so on. These can be leveraged in different ways. In the error example, let’s say you’ve modified the function to be advanced by using the [CmdletBinding()] keyword:

function Do-Something {

[CmdletBinding()]

param( $String )

Write-Error -Message ‘Danger, Will Robinson!’

}

PS> Do-Something

Do-Something : Danger, Will Robinson!

At line:1 char:1

+ Do-Something

+ ~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Write-Error],

WriteErrorException

    + FullyQualifiedErrorId :

Microsoft.PowerShell.Commands.WriteErrorException,Do-Something

When you run this, you’ll immediately see red text that indicates it came from the error stream. Now, let’s silence this error:

Do-Something -ErrorAction SilentlyContinue

The ErrorAction parameter is one of many built-in parameters available with every advanced function. PowerShell functions offer a vast array of capabilities and functionalities. For a deeper understanding and exploration of advanced functions in PowerShell, refer to the built-in PowerShell help system. To access this, use the Get-Help cmdlet, followed by the topic of interest (for example, “about_advanced_functions”).

Mark Fairlie contributed to this article.

author image
Adam Bertram, Senior Writer & Expert on Business Operations
Adam Bertram is an IT expert and business owner who has spent decades advising on network administration and security, designing and building infrastructure, and creating and teaching courses on Windows Server, Powershell and more. While maintaining his own IT business, he has provided hands-on DevsOps services for clients like JPMorgan Chase. Bertram, who has a degree in computer science, holds Microsoft, Cisco and CompTIA credentials. He has written numerous tutorials, guides and books, including "Building Better PowerShell Code: Applying Proven Practices One Tip at a Time."
BDC Logo

Get Weekly 5-Minute Business Advice

B. newsletter is your digest of bite-sized news, thought & brand leadership, and entertainment. All in one email.

Back to top