从PowerShell 1.0访问自定义DLL时出错

时间:2013-10-30 10:34:59

标签: c# powershell

以下是我的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

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

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

 $dll = $($env:userprofile + '\pstest\test.dll')
 [void][Reflection.Assembly]::LoadFile($dll)
 [MyNamespace.MyClass]::Print()

答案 2 :(得分:0)

OOPS我的不好.........

TestClass应该是公开的:(

修改后的工作