且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从PowerShell 1.0中调用的DLL方法

更新时间:2023-08-20 22:16:28

最有可能的方法是一个实例方法,这意味着你将需要有一个类的实例。你可以得到通过在类如公共默认构造函数:

  $ OBJ =新的对象namespace.classname
$ obj.Method()
 

也许唯一的公共consctructor的要求参数,如:

  $ OBJ =新的对象namespace.classname -argstring_arg',7
$ obj.Method()
 

也许没有公共构造,但有一个静态的创建或分析方法,它返回一个实例,例如:

  $的obj = [namespace.classname] ::创建()
$ obj.Method()
 

Actually, I am using a PowerShell version 1.0 script to call a method from a DLL file and used the following code to load the DLL file into PowerShell. [System.Reflection.Assembly]::LoadFile("path of dll") is loded successfully

GAC    Version        Location
---    -------        --------
False  v2.0.50727     location of dll

The class contains a public default constructor. I tried to create an object of the class using the below code.

$obj = new-object namespce.classname

And it throws the following error.

New-Object : Exception calling ".ctor" with "0" argument(s): "The type initializer for 'namespce.classname' threw an exception."
At 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 the method of the class without creating the object, it throws the below error even though the class contains the 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

Most likely the method is an instance method which means you will need to have an instance of the class. You can get that via a public default constructor on the class e.g.:

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

Perhaps the only public consctructor's require parameters e.g.:

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

Or maybe there are no public constructors but there is a static Create or Parse method that returns an instance e.g.:

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