Keeping your PowerShell tidy

I am quite a fan of Powershell but miss the ability to include other files in a simple and clean way.

I quite like the idea that as you run scripts in the different environments dev, test, UAT, staging and production they should never change, the only thing that should change are the variables in each environment to this end I will end up with at least three files per script.

  1. variables – This file contains the things that should and do change in each environment from service accounts, DNS names, environment names & descriptions.
  2. functions – This file will contain reusable blocks of code.
  3. process – This file will contain the process that should not change from environment to environment.

Now the chances are that the variables will be called variables.ps1, functions will be functions.ps1 & process will be called whatever is needed, and if the truth is told the functions.psq1 will be split into different files reflecting the different areas as needed.

The point of this post is not to bore you to death with the way I do work but to show you how to include the variables & functions files into your process script, and how to stop the script if there is an issue, copy and past the following into your Powershell script change as needed and you will be away.

$thisScript = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
 
try
{
    #Load the common variables script. 
    . ($thisScript + '.\variables.ps1')
}
catch
{
    write-host -f red "---------------------------------------------------------------"	
    write-host -f red "|       The variables.ps1 file can not be loaded.             |"
    write-host -f red "|             This script will stop as a result.              |"
    write-host -f red "---------------------------------------------------------------"	
	Break
}
 
try
{
    #Load the common variables script. 
    . ($thisScript + '.\functions.ps1')
}
catch
{
    write-host -f red "---------------------------------------------------------------"	
    write-host -f red "|       The functions.psq file can not be loaded.             |"
    write-host -f red "|             This script will stop as a result.              |"
    write-host -f red "---------------------------------------------------------------"	
	Break
}