5

I created a simple C# dll and registered it using RegAsm.exe. One very simple method is invoked without parameters and returns a number, here is a simplified version.

namespace AVL_test {
    interface ITestClass {
        int GetNumber();
    }

    [ComVisible(true)]
    public class TestClass: ITestClass {
        public TestClass() { }

        public int GetNumber() {
            return 10;
        }
    }
}

I need to invoke that method from Powershell, so I added the type

Add-Type -Path "C:\myPath\AVL_test.dll"

It seems to be loaded because if I [AVL_test.TestClass] I get this output

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False TestClass System.Object

But if I try to invoke GetNumber() by typing[AVL_test.TestClass]::GetNumber() I get this error

Method invocation failed because [AVL_test.TestClass] does not contain a method named 'GetNumber'.

Am I doing something wrong?

1 Answer 1

11

Your method should be static or you need to create an instance of that type (TestClass).

Last can be done using

New-Object -TypeName <full qualified type name> -ArgumentList <args>

Or in your specific case:

$test = New-Object -TypeName AVL_Test.TestClass
$test.GetNumber()
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to implement a static method if I specify the interface? If I try to change method to public static int GetNumber() I get an error saying 'AVL_test.TestClass.GetNumber()' cannot implement an interface member because it is static
No, if there is an interface as in your example, than the method cannot be declared to be static ...
On a related note, I don't think the [ComVisible] attribute is required for PowerShell interaction. You should only need this if you are registering the assembly as a COM object, but PowerShell will load .NET types and assemblies natively.
For the interaface question: You could add a static method, that is called by the interface method - just to provide both scenarios ...
Nice. Is it possible to get the same return value using PowerShell Binary Module? Ie. one that contains/inherits from cmdlet classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.