If you ever came across the task of creating your own module in PowerShell, you most likely faced the problem of running some code in at least two cases:
- Right before you import your module in current PowerShell session; and
- Right before you shutdown your PowerShell session (type exit followed by ENTER)
Root module script runs every time you directly or indirectly call module import:
Thus, it would make sense to let’s say setup aliases to your functions in this script as well as arrange it’s cleanup (and here you have at least two options: when you remove loaded module or when you shutting down your PowerShell session). This script can also be used to maintain the state between PowerShell sessions, e.g. read some settings on module import and dump changed settings on session shutdown. So, here is what it looks like:
Here is a short explanation of what is happening in different sections of this script:
Before Module Import
Here I setup aliases for my functions. Here I read my bookmarks from the file. And here I prettify my prompt a little :)
Before Module Remove
Here I remove all preset aliases, restore the default prompt and try to be nice and keep PowerShell session left without any leftovers. In addition I persist my bookmarks in case they were changed during a session.
Before Session Shutdown
Here I only take care of persisting my bookmarks as on PowerShell session shutdown the “Before Module Remove” code is not called.
Author Roman Kuznetsov
License Roman Kuznetsov