0

以下是我的powershell脚本,

function hello()
{
    $dllpath = "C:\\Documents and Settings\\raj\\pstest\\testlib.dll";
    [Reflection.Assembly]::LoadFrom($dllpath) | out-null;
    $obj = New-Object testlib.TestClass;
    $obj.print();
}

hello

以下是我尝试在 powershell 中访问的 testlib 中的 TestClass

using System;

namespace testlib
{
    class TestClass
    {
        public TestClass()
        {
        }

        public void print()
        {
            Console.WriteLine("Hi");
        }
    }
}

但我收到如下错误,

New-Object : Cannot find type [testlib.TestClass]: make sure the assembly conta
ining this type is loaded.
At C:\Documents and Settings\raj\pstest\script1.ps1:5 char:19
+     $obj = New-Object <<<<  testlib.TestClass;
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentExcepti
   on
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewOb
   jectCommand

You cannot call a method on a null-valued expression.
At C:\Documents and Settings\raj\pstest\script1.ps1:6 char:12
+     $obj.print <<<< ();
    + CategoryInfo          : InvalidOperation: (print:String) [], RuntimeExce
   ption
    + FullyQualifiedErrorId : InvokeMethodOnNull

我曾尝试使用 add-type cmddlet,但它也给出了相同的响应。我猜 dll 已正确加载到 powershell 中,但我无法实例化 TestClass 的对象。请告诉我我做错了什么。

如果我删除 out-null 以下是我得到的输出,

GAC    Version        Location
---    -------        --------
False  v2.0.50727     C:\Documents and Settings\553566\pstest\testlib.dll
New-Object : Cannot find type [testlib.TestClass]: make sure the assembly conta
ining this type is loaded.
At C:\Documents and Settings\raj\pstest\script1.ps1:5 char:19
+     $obj = New-Object <<<<  testlib.TestClass;
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentExcepti
   on
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewOb
   jectCommand

You cannot call a method on a null-valued expression.
At C:\Documents and Settings\raj\pstest\script1.ps1:6 char:12
+     $obj.print <<<< ();
    + CategoryInfo          : InvalidOperation: (print:String) [], RuntimeExce
   ption
    + FullyQualifiedErrorId : InvokeMethodOnNull
4

3 回答 3

0

试试这个: [code]$dll = $($env:userprofile + '\pstest\testdll.dll') 然后尝试从你的库中调用一些静态方法。例如:

于 2013-10-30T10:59:55.823 回答
0
 $dll = $($env:userprofile + '\pstest\test.dll')
 [void][Reflection.Assembly]::LoadFile($dll)
 [MyNamespace.MyClass]::Print()
于 2013-10-30T11:44:24.920 回答
0

哎呀我的坏......

TestClass 应该是一个公共的:(

修改后它的工作

于 2013-10-30T13:16:12.563 回答