0

Powershell is telling me that my parent class is undefined, before it even tries to import that parent class. Details are as follows:

I have two classes, Parent, and Child. Child inherits from Parent.

Parent is located in Parent.psm1. Child is located in Child.ps1.

In Child.ps1, I have a line near the top of the script that says Import-Module C:\Path\To\Parent.psm1

When I try to run .\Child.ps1, Powershell doesn't even run the Import-Module command. Instead, it immediately tells me that the class Parent is undefined, which is obvious because it hasn't imported it yet.

How do I get Powershell to run the Import command before complaining that my classes are undefined?

Strill
  • 228
  • 3
  • 10

2 Answers2

1

This is answered in this post, PowerShell dot source within a dot sourced file - import classes

but taking my above example. It should be like this.

ClassParent.psm1

Class Par1 {
    [string]$blah1 = "you"
    [string]$blah2 = "me"
    Par1(){

    }
}

chi1.ps1

using module C:\Users\tekwi\OneDrive\Documents\Powershell\Tests\ClassParent.psm1

class chi1 : Par1 {
    [string]$child = "balh"

    chi1(){
    }
}

$wee = [chi1]::new();
$wee
Brian H
  • 9
  • 3
-1

Edit. This is correct behavior. See my second response. I can confirm this. If I add the child to the parent, it works fine. If I add the parent to the child, it fails. It didn't matter if I did import-module or . source it. This is on powershell 5.1.

ClassParent.ps1

#Import-Module C:\Users\tekwi\OneDrive\Documents\Powershell\Tests\chi1.ps1

Class Par1 {
    [string]$blah1 = "you"
    [string]$blah2 = "me"
    Par1(){

    }
}

$wee = [chi1]::new();
$wee

chi1.ps1

#Import-Module C:\Users\tekwi\OneDrive\Documents\Powershell\Tests\ClassParent.ps1
. C:\Users\tekwi\OneDrive\Documents\Powershell\Tests\ClassParent.ps1

class chi1 : Par1 {
    [string]$chi1 = "balh"

    chi1(){
    }
}
Brian H
  • 9
  • 3