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 Import-Module
. I tried to arrange Export-Module
with a -class
argument, like the -function
, but there isn't a -class
available. Do I just have to declare the class in every script?
The setup:
import-module holidays
Here is what the class looks like:
Class data_block
{
$array
$rows
$cols
data_block($a, $r, $c)
{
$this.array = $a
$this.rows = $r
$this.cols = $c
}
}
PSA: There is a known issue that keeps old copies of classes in memory. It makes working with classes really confusing if you don't know about it. You can read about it here .
using
is Prone to Pitfalls The using
keyword is prone to various pitfalls as follows:
using
statement does not work for modules not in PSModulePath
unless you specify the module's full path in the using
statement. This is rather surprising because although a module is available via Get-Module
the using
statement may not work depending on how the module was loaded.using
statement can only be used at the very beginning of a "script". No combination of [scriptblock]::Create()
or New-Module
seems overcome this. A string passed to Invoke-Expression
seems to act as a sort of standalone script; a using
statement at the beginning of such a string sort of works. That is, Invoke-Expression "using module $path"
can succeed but the scope into which the contents of the module are made available seems rather inscrutable. For example, if Invoke-Expression "using module $path"
is used inside a Pester scriptblock, the classes inside the module are not available from the same Pester scriptblock.The above statements are based on this set of tests .
ScriptsToProcess
Prevents Access to Private Module Functions Defining a class in a script referred to by the module manifest's ScriptsToProcess
seems at first glance to export the class from the module. However, instead of exporting the class, it "creates the class in the global SessionState instead of the module's, so it...can't access private functions" . As far as I can tell, using ScriptsToProcess
is like defining the class outside the module in the following manner:
# this is like defining c in class.ps1 and referring to it in ScriptsToProcess
class c {
[string] priv () { return priv }
[string] pub () { return pub }
}
# this is like defining priv and pub in module.psm1 and referring to it in RootModule
New-Module {
function priv { 'private function' }
function pub { 'public function' }
Export-ModuleMember 'pub'
} | Import-Module
[c]::new().pub() # succeeds
[c]::new().priv() # fails
Invoking this results in
public function
priv : The term 'priv' is not recognized ...
+ [string] priv () { return priv } ...
The module function priv
is inaccessible from the class even though priv
is called from a class that was defined when that module was imported. This might be what you want, but I haven't found a use for it because I have found that class methods usually need access to some function in the module that I want to keep private.
.NewBoundScriptBlock()
Seems to Work Reliably Invoking a scriptblock bound to the module containing the class seems to work reliably to export instances of a class and does not suffer from the pitfalls that using
does. Consider this module which contains a class and has been imported:
New-Module 'ModuleName' { class c {$p = 'some value'} } |
Import-Module
Invoking [c]::new()
inside a scriptblock bound to the module produces an object of type [c]
:
PS C:\> $c = & (Get-Module 'ModuleName').NewBoundScriptBlock({[c]::new()})
PS C:\> $c.p
some value
.NewBoundScriptBlock()
It seems that there is a shorter, idiomatic alternative to .NewBoundScriptBlock()
. The following two lines each invoke the scriptblock in the session state of the module output by Get-Module
:
& (Get-Module 'ModuleName').NewBoundScriptBlock({[c]::new()})
& (Get-Module 'ModuleName') {[c]::new()}}
The latter has the advantage that it will yield flow of control to the pipeline mid-scriptblock when an object is written to the pipeline. .NewBoundScriptBlock()
on the other hand collects all objects written to the pipeline and only yields once execution of the entire scriptblock has completed.
I found a way to load the classes without the need of "using module". In your MyModule.psd1 file use the line:
ScriptsToProcess = @('Class.ps1')
And then put your classes in the Class.ps1 file:
class MyClass {}
Update: Although you don't have to use "using module MyModule" with this method you still have to either:
Update2: This will load the Class to the current scope so if you import the Module from within a function for example the Class will not be accessible outside of the function. Sadly the only reliable method I see is to write your Class in C# and load it with Add-Type -Language CSharp -TypeDefinition 'MyClass...'
.
The using statement is the way to go if it works for you. Otherwise this seems to work as well.
Use a function to deliver the class
class abc{
$testprop = 'It Worked!'
[int]testMethod($num){return $num * 5}
}
function new-abc(){
return [abc]::new()
}
Export-ModuleMember -Function new-abc
Import-Module path\to\testclass.psm1
$testclass = new-abc
$testclass.testProp # Returns 'It Worked!'
$testclass.testMethod(500) # Returns 2500
$testclass | gm
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
testMethod Method int testMethod(System.Object num)
ToString Method string ToString()
testprop Property System.Object testprop {get;set;}
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).
This certainly does not work as expected.
The idea in PowerShell 5 is that you can define your class in a separate file with a .psm1 extension.
Then you can load the definition with the command (eg):
using module C:\classes\whatever\path\to\file.psm1
This must be the first line in your script (after comments).
What causes so much pain is that even if the class definitions are called from a script, the modules are loaded for the entire session. You can see this by running:
Get-Module
You will see the name of the file you loaded. No matter if you run the script again, it will not reload the class definitions! (It won't even read the psm1 file.) This causes much gnashing of teeth.
Sometimes - sometimes - you can run this command before running the script, which will reload the module with refreshed class definitions:
Remove-Module file
where file is the name without path or extension. However, to save your sanity I recommend restarting the PowerShell session. This is obviously cumbersome; Microsoft needs to clean this up somehow.
I've encountered multiple issues regarding PowerShell classes in v5 as well.
I've decided to use the following workaround for now, as this is perfectly compatible with .NET and PowerShell:
Add-Type -Language CSharp -TypeDefinition @"
namespace My.Custom.Namespace {
public class Example
{
public string Name { get; set; }
public System.Management.Automation.PSCredential Credential { get; set; }
// ...
}
}
"@
The benefit is that you don't need a custom assembly to add a type definition. You can add the class definition inline in your PowerShell scripts or modules.
The only downside is that you will need to create a new runtime to reload the class definition after is has been loaded for the first time (just like loading assemblies in a C#/.NET domain).
The way I've worked around this problem is to move your custom class definition into an empty .ps1 file with the same name (like you would in Java/C#), and then load it into both the module definition and your dependent code by dot sourcing. I know this isn't great, but to me it's better than having to maintain multiple definitions of the same class across multiple files...
To update class definitions while developing, select the code for the class and press F8 to run the selected code. It is not as clean as the -Force
option on the Import-Module
command.
Seeing as using Module
doesn't have that option and Remove-Module
is sporadic at best, this is the best way I have found to develop a class and see the results without having to close down the PowerShell ISE and start it up again.
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 Import-Module
. I tried to arrange Export-Module
with a -class
argument, like the -function
, but there isn't a -class
available. Do I just have to declare the class in every script?
The setup:
import-module holidays
Here is what the class looks like:
Class data_block
{
$array
$rows
$cols
data_block($a,$r,$c)
{
$this.array = $a
$this.rows = $r
$this.cols = $c
}
}
A surprising & cumbersome limitation of using module
appears to be that any classes to expose outside of a module MUST be in the module's psm1 file itself.
A class definition to expose outside the module cannot be 'dotsourced' into the psm1 file from a separate ps1 file in the module
...this is as per the docs since v5.1 (to at least 7.2):
The using module statement imports classes from the root module (ModuleToProcess) of a script module or binary module. It does not consistently import classes defined in nested modules or classes defined in scripts that are dot-sourced into the module. Classes that you want to be available to users outside of the module should be defined in the root module .
So therefore, it seems the simplest options (as discussed in other answers) are:
If you only need to reference class instances outside of its defining module, create public functions to return class instances:
function Get-MyModulesClass { [MyModuleClass]::New() }
To reference a class type outside of the module (eg specifing a function argument's type), the class must have been defined directly in the psm1 file of the module, and this psm1 file must have been included in your external script via using module
(eg using module <relativePathToModulePsm1File>
).
...and of course what doesn't help when figuring all this out is that classes don't reload so you need start a new powershell session every time you make a change to the classes.
class MyPrivateClass {
[void] Test(){ Write-Host "Accessed private class methods!"}
}
class MyPublicClass {} # Exposed classes MUST be defined in this file
. $PSScriptRoot\MyPrivateClass.ps1
function Get-MyPrivateClassInstance { [MyPrivateClass]::new()}
using module .\MyLibraryModule\MyLibraryModule.psm1
[MyPublicClass]$myVar1 # Works
[MyPrivateClass]$myVar2 # Errors
Import-Module .\MyLibraryModule\MyLibraryModule.psm1
$object = Get-MyPrivateClassInstance
$object.GetType().Name
$object.Test() # works
InvalidOperation:
Line |
5 | [MyPrivateClass]$myVar2 # Errors
| ~~~~~~~~~~~~~~
| Unable to find type [MyPrivateClass].
MyPrivateClass
Accessed private class methods!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.