On all of my previous posts, I showed you that the files had common code on their top parts. I said we don't touch those parts usually and that we duplicate them from one example to another. That's true, but as our code grows more complex we need to adjust some things in our PS code (with the Xaml code, it still makes sense to keep duplicating the top window tag).
As we progress with our complex projects, lots of functions, common to many projects, are being added to the PS code. We need to have a place to put those common functions so we can reuse them on all our future apps. The solution is to create a new PS file, call it with a meaningful name (I'm calling mine CommonFunctions.PS1). This file will hold all of the reusable functions we create plus the assemblies load. The first line of the code will load all the files starting with "Common" into our app's PS file. Later on, if we decide to add more common content, we just give is a name that starts with "Common" and it will be included in the code.
The way to include this external code in our PowerShell script is either through Dot-Source or as a module we create and import. There is an argument between PS developers on what is the right way to do it. There are people who are strongly against Dot-Sourcing. The word is that it's faster to load a module.
My opinion is that Dot-Sourcing is much simpler and for 3,000 lines of code to include it's a matter of being 100 milliseconds faster. Doesn't worth it.
The basic syntax to include a file via Dot-Sourcing is:
. "LocationToTheFile\Filename.ps1"
The "dot" in the beginning does the trick.
Just make sure you always keep the latest common files in your project's folder.
What I usually do is name all of my common files with a "Common" prefix, like CommonFunctions.ps1 etc. , keeping them in the app's root folder and then dot-source them in one command:
Get-ChildItem -Path $PSScriptRoot -Filter Common*.ps1 |
ForEach-Object {. ($_.FullName)}
Comments