I’m in the middle of a project that requires me to read over existing PowerShell scripts and provide edits. This means I need to add error checking, remove unnecessary duplication, and break down lengthy scripts into tighter, singled purposed functions. After breaking down the first script into three functions and therefore concerned we’re going to have a lengthy list of independent functions to execute, I had an idea to make things easier. I’ve said it before: I’d rather troubleshoot five 20 line functions, than one, one hundred line script.
The below example creates five basic, basic functions. Each of these Show-*Number functions writes a single string to the host when invoked. The problem here, is that I’m required to remember the names of each of the functions and their order. This example uses fairly easy to remember names, and the order is pretty straightforward, too. Even so, in some situations they won’t always be so easy to recall, to include their order. I understand we have various tools for command discovery, but I want a simpler way.
Function Show-FirstNumber { 'This is sequence 1.' } Function Show-SecondNumber { 'This is sequence 2.' } Function Show-ThirdNumber { 'This is sequence 3.' } Function Show-FourthNumber { 'This is sequence 4.' } Function Show-FifthNumber { 'This is sequence 5.' } PS > Show-FirstNumber This is sequence 1. PS > Show-SecondNumber This is sequence 2. PS > Show-ThirdNumber This is sequence 3. PS > Show-FourthNumber This is sequence 4. PS > Show-FifthNumber This is sequence 5.
That simpler way, is to create a single function that has the job of invoking all of the other functions. I suspect you may have thought of this too, but if not, well then, there we go. Now, all my users need to know about is the Start-Sequence function defined below.
I’m out to “hide” those other functions. I want to say I took your three scripts, and now you can run them all with this single function. The user may not even know their single invocation just ran several separate functions, and that’s, fine with me.
Function Start-Sequence { 'Starting the sequence.' Show-FirstNumber Show-SecondNumber Show-ThirdNumber Show-FourthNumber Show-FifthNumber 'Ending the sequence.' }
When the Start-Sequence function is invoked, it’ll remember the names of those other functions for us, and best of all, I won’t be required to the do the same. Here’s our results now. It’s one single command, running multiple functions, getting the entire job done, and making things much easier to troubleshoot later on.
PS > Start-Sequence Starting the sequence. This is sequence 1. This is sequence 2. This is sequence 3. This is sequence 4. This is sequence 5. Ending the sequence.
Anyway, back to breaking apart some scripts.