Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create C# dll and use method with powershell

Tags:

c#

powershell

dll

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?

like image 966
Naigel Avatar asked Jan 09 '23 10:01

Naigel


1 Answers

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()
like image 105
Markus Avatar answered Jan 15 '23 18:01

Markus