Managing complexity

The approach of placing your functions into separate directories might look like it increases the complexity, but it actually reduces it. It is far more complex to maintain a script of hundreds of lines of code. It gets even worse when the code is being duplicated, due to laziness or a lack of knowledge. Duplicated code means duplicated risks, and duplicated maintenance, as well.

There is a very helpful module called PSModuleDevelopment on GitHub, which contains some refactoring functions. One of those functions is Split-PSMDScriptFile, which will automatically extract all functions into separate script files for you.

Check it out on the PowerShell Gallery!

With existing scripts, it is very important that you discover such candidates for refactoring. These duplicated code bits will probably be the first functions that you create. When starting from the drawing board, you can always keep the best practices in mind and start off with proper functions.

In order to tackle seemingly complex problems, try to break them into smaller pieces. Remember CRUD from the section on APIs? Most things that you want to accomplish will likely require you to read data, create objects, update objects / write back to some infrastructural components, and delete objects. These four keywords already hint at the cmdlet verbs that you will be using quite often in the beginning: get, new / add, set, and remove.

In order to keep the complexity relatively low, try to refrain from creating functions that do everything. The design philosophy of cmdlets is this: a cmdlet should have one purpose, and fulfill its purpose flawlessly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.42.94