Powershell Live Code Loading (kind of)

Hot code loading is a feature of languages that allows a developer to load new code into a running system without stopping the process. This has some clear benefits on servers, security and feature patches can be added without a risk of downtime. Yes, building your application in a way that you can fail over to a secondary system but that never seemed kosher to me as a patching strategy unless you're working at scale and already account for high availablity. I've implemented some long runner server software in PowerShell and using some of the features it's gleaned from Unix scripting you can hot load new code into them on the fly.

So walkthing through the example, we have an infinate loop that keeps the process from exiting. Inside of the loop, the script gets a list of all ps1 scripts in the funcs folder, storing them in an array. Then it enumeratest that list and dot sources each script into an array. It then enumerates the array and calls the .Invoke() method on each object, passing "Hello World!" as an argument. This allows you to put an abitrary amount of scripts inside the funcs folder, pass them some state and execute their code. The funcs scripts need to be structured in a specific way:

# wrap code in a block, basically an anonymous function
    param ($in)
Write-Host $in -ForegroundColor Green


Wrapping the code in curly braces is what allows you to dot source the script file into an object, to be invoked later. The other nice side effect of this style is that you can have state that is scoped locally to the script's function. There are some downsides though: still nothing preventing the dynaically loaded scripts from polluting global state, does not take advantage of pipelining, execution order will depend on filename.

While this approach can be useful, it's still not right for all use cases, but this can be a powerful tool for debugging. Even if you aren't loading all the scripts in a file, having a single file that executes from a dot include statement inside a loop opens up the ability to change configuration settings and output different status information. Dot include files are a powerful tool for rapidly itterating on a script and the best way I've found to develop a long running PowerShell utility.