Maintaining Module Specific Settings in PowerShell Session

Posted in category powershell on 2013-08-26
Tags: powershell

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:

Let’s have a look at a small example from RootModule.psm1 root module script of KuCommon module (KuModule’s project).

Root module script runs every time you directly or indirectly call module import:

Import-Module KuCommon

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:

# -- setup aliases
Set-Alias -Name:"e" -Value:"Open-Explorer" -Scope:Global
Set-Alias -Name:"n" -Value:"Open-TextEditor" -Scope:Global
Set-Alias -Name:"g" -Value:"Invoke-Bookmark" -Scope:Global
Set-Alias -Name:"f" -Value:"Find-InPaths" -Scope:Global
# -- restore bookmarks if any
# -- pretify prompt
$Global:prompt_old = Get-Content Function:\prompt
Set-Content Function:\prompt KuPrompt
$ExecutionContext.SessionState.Module.OnRemove = {
  # remove aliases
  Remove-Item Alias:\e
  Remove-Item Alias:\n
  Remove-Item Alias:\g
  Remove-Item Alias:\f
  # -- restore default prompt
  Set-Content Function:\prompt $Global:prompt_old
  # -- backup bookmarks
$null = Register-EngineEvent -SourceIdentifier ( `
[System.Management.Automation.PsEngineEvent]::Exiting ) -Action `
{ `
  # -- backup bookmarks
  Write-Bookmarks `

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.