How to call a DLL method from PowerShell 1.0

I use a PowerShell version 1.0 script to call a method from a DLL file and used the following code to load a DLL file into PowerShell.

[System.Reflection.Assembly]::LoadFile("path of dll") is loaded successfully GAC Version Location --- ------- -------- False v2.0.50727 location of dll 

The class contains the default public constructor. I tried to create a class object using the following code:

 $obj = new-object namespce.classname 

And this causes the following error:

New-Object: Exception throws ".ctor" with argument "0": "The type initializer for" namespce.classname "threw an exception."
On line: 1 char: 18
+ $ obj = new object <<<namespce.classname
+ CategoryInfo: InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId: ConstructorInvokedThrowException, Microsoft.PowerShell.Commands.NewObjectCommand`

When I tried to call a class method without creating an object, it throws the following error, even if the class contains a method:

 PS C:\Windows\system32> [namespace.classname]::method() Method invocation failed because [namespace.classname] doesn't contain a method named 'method'. At line:1 char:39 + [namespace.classname]::method <<<< () + CategoryInfo : InvalidOperation: (method:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound 

This is a version error, usually a problem with the version of the DLL. Dot NET does not allow unloading the same for powershell. So, the reboot will start and fix. Just avoid the same problem without guaranteeing ambiguity of versions.

+4
source share
1 answer

Most likely, a method is an instance method, which means you will need to have an instance of the class. You can get this through the standard default constructor in the class, for example:

 $obj = new-object namespace.classname $obj.Method() 

Perhaps the only public constructor requires parameters, for example:

 $obj = new-object namespace.classname -arg 'string_arg',7 $obj.Method() 

Or maybe there are no generic constructors, but there is a static Create or Parse method that returns an instance, for example:

 $obj = [namespace.classname]::Create() $obj.Method() 
+2
source

Source: https://habr.com/ru/post/1496204/


All Articles