2

I want to use a custom class I declared in a different file as a type:

emailhelper.ps1

class EmailInfo
{
    [string]$subject;
    [string]$body;
    [System.Collections.Generic.List[string]]$distributionList;
}

myfile.ps1

."$PSScriptRoot\.\emailhelper.ps1"

class MyClass
{
    [EmailInfo]$startEmailInfo;
    ...

    MyClass([EmailInfo] $info)
    {
     ...
    }
}

But it seems not to find it:

En C:\xxx\yyyy\myscript.ps1: 64 Carácter: 6
+ [EmailInfo]$info;
+ ~~~~~~~~~ Cannot find the type [EmailInfo].

The strange thing is that I can create new objects without any problem:

$emailInfo = New-Object EmailInfo;

So the problem seems to be related to using "EmailInfo" as a type.

Finally, if I add "EmailInfo" to the myscript.ps1, that is, the same file where the class is being used, then I can use it as a type...

So, how can I use a class defined in a different file as a type?

G42
  • 9,791
  • 2
  • 19
  • 34
Luis
  • 2,833
  • 3
  • 27
  • 41
  • 2
    IMO, you will have to put your `custom class` in a `custom PowerShell Module` and then import it as shown [here](https://stackoverflow.com/questions/31051103/how-to-export-a-class-in-powershell-v5-module). If you don't have `PoSh` version 5, see [this](https://info.sapien.com/index.php/scripting/scripting-classes/import-powershell-classes-from-modules). See if it helps in any way. – Vivek Kumar Singh Mar 01 '18 at 20:19

1 Answers1

0

The simplest solution is to use the using keyword, at the very beginning of your script :

using module .\path\to\your\Module.psm1

Path can be relative from your current file.

To prevent caching problem, use powershell.exe .\script.ps1 to execute it, even in the PoweShell ISE console.

fred727
  • 2,644
  • 1
  • 20
  • 16