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

Home

Understanding Functions in PowerShell

Adam Bertram
business.com Contributing Writer
Sep 04, 2018

Instead of copying and pasting the same code over and over again, create a PowerShell func

Instead of copying and pasting the same code over and over again, create a PowerShell function.

When first starting out writing PowerShell scripts you're not necessarily concerned about things such as modularity, reusability and "best practices." You're just getting your feet wet. However, as time goes on, you'll soon realize that you begin repeating yourself in code.

You'll notice that the need to do the same thing over and over keeps getting greater. You could just copy and paste that same code, but it's not sustainable. Instead, why not create small "building blocks" in code so that they can be reused? It's time to start creating PowerShell functions.

A function in PowerShell is a grouping of code that has an optional input and output. It's a way of collecting up a bunch of code to perform one or many different times by just pointing to it instead of duplicating that code repeatedly.

Basic functions

There are two kinds of functions in PowerShell. We have a "basic" function and an advanced function. "Basic" functions are the simplest form of a function that can be created. They don't have any of the fancy built-in capabilities that advanced functions do. It is created or declared by using the function statement followed by a set of curly braces.

function Do-Something {}

The above is technically a function that can then be called by invoking Do-Something but as you'll find 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 to ensure it does something. To demonstrate, I'll use the Write-Host command that writes text to the PowerShell console.

function Do-Something {
    Write-Host 'I did something!'
}

PS > Do-Something
I did something!

Now you can see above that when invoked; it runs the code inside of the function. What if we'd like to pass something into the code inside of the function when it's running? We can create one or more parameters inside of a parameter block.

function Do-Something {
    param( $String )
   Write-Host "I did something -- $String!"}

PS > Do-Something -String 'thing'
I did something -- thing!

Notice that I specified the String parameter by adding a dash followed by the parameter name followed by the value right after I called Do-Something. This is the basics of passing parameters to functions.

Advanced functions

Basic functions work, but most of the time you'll find yourself creating advanced function. Advanced functions are functions that include all of the functionality as basic functions but also come with some built-in features that basic functions do not. 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 we want to display an error message if something happens inside of the function. However, we also want the ability to hide this error message for some reason at only certain times. With a basic function, it would be kludgy to do this. However, with an advanced function, that functionality is built right in. Advanced functions, by default, already have parameters even if you don't include them like Verbose, ErrorAction, WarningVariable and so on. These can be leveraged some different ways. In our error example, let's say I've modified our 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 this is run, you'll immediately see red text which indicates it came from the error stream. Let's now silence this error.

Do-Something -ErrorAction SilentlyContinue

The ErrorAction parameter is just one built-in parameter on every advanced function. There's so much more to PowerShell functions we didn't get time to cover. For a full breakdown of everything that advanced functions can do for you, refer to the about_advanced_functions help topic.

Image Credit: Atstock Productions/Shutterstock
Adam Bertram
business.com Contributing Writer
Adam Bertram is a 20-year veteran of IT and experienced online business professional. He's an entrepreneur, IT influencer, Microsoft MVP, blogger, trainer and content marketing writer for multiple technology companies. Adam is also the founder of the popular IT career development platform TechSnips. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn, or follow him on Twitter at @adbertram or the TechSnips Twitter account at @techsnips_io.