jason jason - 2 months ago 25x
Powershell Question

how to export a class in powershell v5 module

I've got a module setup to be like a library for a few other scripts. I can't figure out how to get a class declaration into the script scope calling

. I tried to arrange
with a
argument, like the
, but there isn't a
available. Do I just have to declare the class in every script?

The setup:

  • holidays.psm1 in ~\documents\windows\powershell\modules\holidays\

  • active script calls
    import-module holidays

  • there is another function in holidays.psm1 that returns a class object correctly, but I don't know how to create new members of the class from the active script after importing

Here is what the class looks like:

Class data_block
$this.array = $a
$this.rows = $r
$this.cols = $c


You pretty much cannot. According to about_Classes help:

Class keyword

Defines a new class. This is a true .NET Framework type. Class members are public, but only public within the module scope. You can't refer to the type name as a string (for example, New-Object doesn't work), and in this release, you can't use a type literal (for example, [MyClass]) outside the script/module file in which the class is defined.

This means, if you want to get yourself a data_block instance or use functions that operate those classes, make a function, say, New-DataBlock and make it return a new data_block instance, which you can then use to get class methods and properties (likely including static ones).