What am I doing wrong here - or does PowerShell v5 not support separate class files and inheritance?
foo.ps1:
class foo
{
[STRING] $test = 'Hello World';
[STRING] PrintTest()
{
return $this.test;
}
}
bar.ps1:
Import-Module "$PSScriptRoot\foo.ps1"
class bar : foo
{ }
CONSOLE
PS C:\Script> Import-Module ./bar.ps1;
PS C:\Script> $myBar = New-Object bar;
PS C:\Script> $myBar.PrintTest();
Method invocation failed because [bar] does not contain a method named 'PrintTest'.
If it put the foo and bar classes in the same file it works fine. However the classes I'm building are rather large and I want to separate them.
Import Classes using Using Module Statement The assembly-importing feature is a convenience; the module-importing feature is a requirement, because there's no other way to import classes from script modules. The Using statement has a module parameter that takes a module name string or a ModuleSpecification object.
The using statement allows you to specify which namespaces are used in the session. Adding namespaces simplifies usage of . NET classes and member and allows you to import classes from script modules and assemblies. The using statements must come before any other statements in a script or module.
The Import-Module cmdlet adds one or more modules to the current session. Starting in PowerShell 3.0, installed modules are automatically imported to the session when you use any commands or providers in the module. However, you can still use the Import-Module command to import a module.
Since PowerShell 5 you are able to create your own classes in PowerShell. Although classes in other programming languages are a big advantage and sometimes even required, they are not required in PowerShell. In some cases you may want to use classes in PowerShell to create objects that can be used in PowerShell.
Firstly, a module file should have the extension .psm1
so you're going to want to change that. If you do not name them this way, the Using
statement I referenced below will show an error.
bar.psm1 should contain a reference to the module, because modules do not import classes.
bar.psm1:
Using module ".\foo.psm1"
class bar : foo
{ }
However once you do this, the bar class is not exported so you would have to write a separate ps1 file that stated at the top Using module ".\bar.psm1"
and then inside that script file you could call the [bar] class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With