Search code examples
c#powershellexceptionadd-type

Rerencing a class from a Add-Type'd class gives error


I have one C# class (processcontroller.cs).

In this class I add other classes to a list object (these classes will be invoked later).

One of my sub classes looks like this:

namespace PowerShellTests
{
    public class Step1
    {
        public void Initialize()
        {
            try
            {
                File.Open("filethatdoesnotexist.txt", FileMode.OpenOrCreate);
            }
            catch (Exception exc)
            {
                ExceptionHandler.LogException(exc);
            }
        }
    }
}

I define my process controller path and then set it's first sub class like so:

processController.steps[0] = $Step1Class

I define $Step1Class with the following 3 PS commands

$script = [io.file]::readalltext('step1.cs')
add-type $script -lang csharpversion3
$Step1Class = New-Object Step1

However on the last line of the above code I get an error:

The name ExceptionHandler does not exist in the current context.

I understand why the error is firing, but other than having ExceptionHandler defined in the Step1 class itself what other options do I have? The reason I do not want to have it defined in Step1.cs is because that will mean I have to repeat it for every other step class.


Solution

  • My guess is that Powershell has no reference to your custom class (providing that it is a custom class). Try compiling it and loading it in as a assembly.

    [System.Reflection.Assembly]::LoadFrom("path to assembly")