Please feel free to provide feedback or file bugs here.

Package PowerShell Classes in a Module

Object Oriented Programming seems to be supported now in PowerShell, but custom classes defined in modules don't seem to behave the way they should.

There only seem to be two consistent ways to make these work when importing a module that has classes defined:
1. Import the module, then run "using module ..." to make the classes available in the session. Alternatively, you can import the module with the using statement, but this isn't ideal (no versioning).
2. Add the class definition file(s) to the ScriptsToProcess attribute of the module. This isn't ideal either as it runs the scripts in the global session which is bad practice.

Please provide a method that allows classes to be packaged with a module to support OOP scenarios. Thanks!

32 votes
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)

    We’ll send you updates on this idea

    Matt M. shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    2 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...
      • Anonymous commented  ·   ·  Flag as inappropriate

        Keyword "using" work fine
        But import-module should also import classes (not just functions)

      • Wim commented  ·   ·  Flag as inappropriate

        The behaviour is also inconsistent.

        When you create a binary PowerShell module, just by compiling a simple, barebones C# class DLL and adding it to the module path (even without manifest), the class objects inside the DLL will be immediately available after import-module for that session.

        When you create a 'classic' PowerShell module (using .psm1/.psd1) the classes inside the module are only available to that module internally, but not the PS session by default, unless you run the 'using module ...' command in the PowerShell session.

        That by itself is already inconsistent. It gets more confusing when you create a new object using New-WebserviceProxy. The associated classes from the online web service are from then on also available in the current session, without any extra loading.

        So, classes in 'foreign' modules are autoloaded and available, while 'PowerShell native' classes are not.

        It would be great if the 'Export-ModuleMember' command was expanded to support classes as well.

        I have a feeling this is an oversight. I spoke to someone at the PowerShell booth at Microsoft Ignite 2016 and the person was surprised classes inside text based .psm1 files are not available outside the module by default.

      Feedback and Knowledge Base