Using Class

Hi Everyone,

I have this Log Class in a .psm1 file, in the ‘Bin\Log’ folder:

c:\Program\Bin\Log\Log.psm1:

Class Log
{
	LogToFile()
	{
		
	}
}

Another class in a .psm1 file, in the ‘Bin\Mycar’ folder.

c:\Program\Bin\Car\MyCar.psm1:

using module c:\Program\Bin\Log\Log.psm1
Class MyCar
{
	DoStuff()
	{
		[Log]::DoStuff()
	}
}

And the PS1 file to wrap up everything.

c:\Program\start.ps1

using module c:\Program\Bin\Car\MyCar.psm1
using module c:\Program\Bin\Log\Log.psm1
[Log]::DoStuff()
[MyCar]::DoStuff()

Importing the classes from the PSM1 files with the “using module” command in the PS1 file works just fine, but if I want to use the Log Class within the MyCar class, it doesn’t work.

What am I doing wrong ?

Thanks in advance.
Nuno

It’s a bit tricky to do this with the classes in separate files. Typically what I see done is that when someone builds a module, the classes/enums/etc are often all compiled into a single file during the build step of their publishing pipeline.

This helps to circumvent the weird issues with classes like this.

All the imported files from the ps1 start script work fine… The problem is when I use a relative path from another psm1.

I have a psm1 file with a Log class which I need to use everywhere.

How am I supposed to use the class.

 

 

You log class doesn’t have a DoStuff method defined.

Try inheritance.

using module c:\Program\Bin\Log\Log.psm1
Class MyCar:Log
{
	DoStuff()
	{
		$this.LogToFile()
	}
}

It’s not so much that OP wants one class to inherit another. They want one class to return an object type of the other as the returned object from a method… if I’m understanding the intention here.

If you need a relative path, I’d make use of $PSScriptRoot; relative paths are fragile and easily break.

 

I have already tried the $psroot. It does not work in the using module. :frowning:

I only need to log all errors from all my classes, which are in separated files in different folders. Using the full path for the log class file work. But if I move the script to another computer/location I have to change all references…

Put the path in quotes?

using module "$PSScriptRoot\ClassFile.psm1"

[Powershell] “$PSScriptRoot\Modules\Log\RooxLog.psm1” is not a valid value for using name.