PowerShell Functions (part 1)

Welcome to my introduction on PowerShell Functions. Functions are the easiest way to write scripts that have reusable code. As you write your scripts you will see them grow and develop over time, especially if needs keep changing and your scripts need regular updating.

Functions can be very simple in nature and range from displaying your current PowerShell version to returning certain contents of a specific file, or even update Active Directory atributes for all your users. Functions will make your code that much easier to read. Personally, if my scripts are complex, I will keep all my functions in a seperate file. It’s a good idea to keep track of your function names and their purpose so you don’t double up on the names.

So lets start with an easy one. On the Microsoft docs page they have a basic one that will return your currect PowerShell version, as detailed below:

This simple function is called by typing

Which will return the following:

While the above funtion is a bit basic but also a good example, I thought we might try something a little more useful (depending on your needs). The function below is handy if you are looking up a users details but you are not sure of all the details, you have a partial name or email address, their telephone number or extension, department or title.

Here is a little one I use quite often, and you can change the variables to check as you see fit

The above may look complicated but if you take it apart and look at it as if you are only looking up the username and email address of the person, then it would look like this

To run the above code just type the function name and the name of the user account you want to look up in Active Directory

Copy the code above and play with it and see how easy it is to use. Remember, every time you edit the function you will need to rerun it.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.