Automating the import-module call

If you’ve read my previous post on Powershell folder structure, then you may have noticed I mentioned automating the import-module call.

Whenever you’re coding a large amount of functions, 2 organizations come to mind:

  1. Function & Non-function .ps1 script files
  2. Modules .psm1; Function collections

Storing functions by name in your .ps1 script file or coding the Param() directive at the beginning of your script file and naming your files based on the function they provide is a sound strategy; but might become cumbersome to manage once you’re hitting dozens of functions.

Storing functions in module files allows for a more detailed level of organizational hierarchy. Naming your functions, in a mod- prefixed .psm1 file, e.g. mod-Files.psm1, mod-System.psm1, mod-Audit.psm1. provides an easy structure to iterate through and organize by module and function name.

All of this comes together in your global.psm1, which should be stored in .\{root}. Here’s how to load your framework in a single global call:

Some of the contents of your .\global.psm1 file…

#Set libraries root.
$root = Get-Item ".\LIBRARIES"

#Loop through root and import.
foreach ($folder in $root) {
   Import-Module ( 
            Get-ChildItem $folder -Include "*.psm1"  -Recurse 
        ) -DisableNameChecking    

Place the above code in a .\global.psm1 file at the root of your folder structure (Solutions folder), and then run the following command in powershell console:

import-module .\global.psm1 -DisableNameChecking

And presto. All you have to do from this point is just continue focusing on adding modules with functions in your lib- subfolders under {root}\LIBRARY. Whenever you import .\global.psm1, you import your entire framework.

Offload your powershell code Powershell folder structure

No Comments

No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *