Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Class Inheritance from separate file using Import-Module

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.

like image 708
Vidarious Avatar asked Aug 23 '17 20:08

Vidarious


People also ask

How do I import a class in PowerShell?

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.

What is $using in PowerShell?

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.

What is import module in PowerShell?

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.

Can you create classes in PowerShell?

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.


1 Answers

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.

like image 140
Shawn Esterman Avatar answered Sep 26 '22 07:09

Shawn Esterman