PowerShell Dot Sourcing

My career in IT started in Software Development and most of the time I take for granted some of the common practices and basics of programming that I learnt are also clear for every one of my IT Pro colleagues.

In brief, as developers, when we try to solve problems we define objects and writing source code we describe them into classes. That class definition has attributes and methods that let us interact with that object.

I don’t need to go any deeper and refer to any of the principles of the Object Oriented Programming (OOP), but I can guarantee that knowing them will not hurt you at all! Instead will be very helpful once your script will need to call .NET Framework classes within PowerShell.

In software engineering there is a very simple and popular principle called DRY (Don’t Repeat Yourself). With a DRY approach we try to solve problems defining objects or create functions that we can re-use later and it offers a level of abstraction, we write better and more readable code and last but not least we avoid useless redundancy.

But how can we re-use functions without copying them in every single script? How can we structure script as a developer would do?
As you can probably guess the answer is Dot Sourcing.

Essentially is just a way to reference and include another script into one another. In other programming languages are usually placed at the start/top of the script with a keyword as: include, using, import, etc..

But let’s start with a simple example. This is my PowerShell Script called Test-DotSourcing.ps1. To avoid any confusion I’ve saved the powershell script differently than the function name.

When I need to call or re-use that function I can reference with . a space and the file path of the powershell script they I wish to include.

After I’ve imported the script I can call the function that will return the name of our workstation or server.

Yes, is just that simple!

Return to : PowerShell Learning and Security Features

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.