Donnerstag, 25. März 2010

PowerShell modules are funny guys

Ed Wilson says Windows PowerShell 1.0 was the vision, Windows PowerShell 2.0 is the reality [ from the preface of LeeHolmes Windows PowerShell Cookbook
I dare say PowerShell 2.0 ISE and Modules are still a vision.

When a module depends on a another module like SQLISE on ICECreamBasic or WPK it seems natural
to use within the .psm1 file
import-module ISECreamBasic            
import-module SQLParser
import-module adolib
import-module WPK


When I write a second module OracleIse, I can do similar

import-module ISECreamBasic            
import-module OracleClient
import-module WPK


Seems OK so far.

Next modules can be removed using Remove-module and that fires even an event to do some clean up as removing ISE addons menu items

$mInfo = $MyInvocation.MyCommand.ScriptBlock.Module            
$mInfo.OnRemove = {
Write-Host "$($MyInvocation.MyCommand.ScriptBlock.Module.name) removed on $(Get-Date)"
Remove-IseMenu OracleIse
}


Now emove on of these modules an see, which modules are left using

get-module            


You see, that the removed modul removed the modules imported within too, without tribute to the fact that the other module depends on WPK and ISECreamBasic too.

Conclusion. Better do not use import-module to import module from within your modules. Import the needed modules in advance.

Have some fun trying to find work arounds for this issue.

Bernd

Kommentare:

  1. This is exactly how I would expect PowerShell to act. Anything loaded by a module should get unloaded when that module is removed (if at all possible).

    If you have external dependencies, you should declare them in a manifest module. But there could be more work done on declaring dependencies.

    AntwortenLöschen
  2. Thank you, Archer.
    I investigated a little further. When a modul depends on other modules, one way to ensure this, is to import the module within the first.
    To modules working this way don't interfer with each other.

    But when you first load some module, to be present for interactive users. And in the following Import and Remove a module which import on of these modules, the module is removed. So it is very difficult to ensure that some modules are loaded, when removing of modules is allowed.

    I dare say that this is an error in the design.
    When a modul only loaded a nested module, it ought not be allowed to remove the same module from global context.

    AntwortenLöschen