This post is part 4 in an open ended series on PowerShell for IT Pros. It is intended to be a framework to learn from, not an exhaustive study guide. Consider it a survey in what's possible, not a master's class in all things PowerShell. You can find the first post in the series here.
It’s taking everything in me right now to not break into School House Rock’s “Conjunction Junction,” but unfortunately this post is about functions, not conjunctions.
A function in PowerShell is a block of code that you can call from within a script. Parameters can be passed into a function, and it can be called any number of times. I typically write functions for one of two different purposes: either I need to run the same block of code multiple times in the same script, or I plan on reusing the code block in multiple scripts.
Functions are essentially scripts that are included as part of a larger script. You will often hear experienced scripters talking about building a toolbox. For many of us, that is a collection of scripts and functions that we reuse regularly. For example, I have several different functions that I use as source material for other scripting project. I have a logging function, a function that writes an exit code to the registry, and functions to build PowerShell objects. Some of these, like the logging and exit code functions, can be plugged into a script with almost no changes. The PS Object function usually needs to be customized based on the script I am work on. Whether a function needs to be edited or can be plugged directly into another script – they all save time and assist with common tasks.
A function can be as simple as a single cmdlet, or as complex as many scripts. Generally, I like to keep my functions simple. If it needs dozens of lines, it may be best broken out into small functions. Conversely, if a task can be handled in one or two cmdlets, it may be harder to justify handling it in a function. In this post we are going to explore a relatively simple function, building off the Connect-AzureAD cmdlet from my previous post.
My name is Sean Bulger. I am an IT Pro that has worked in the Modern Endpoint Management work space since 2015. I have worked in various environment, ranging from mature enterprise all the way down to a fledgling IT organization looking to find their way in a cloud first world. Before rejoining the technology field in 2014 I had a wide range of careers - from plumber to paramedic - that have helped to shape my perspective on the world.