无法从Powershell 3.0调用C#类

时间:2017-09-11 16:19:47

标签: c# powershell

我创建了一个简单的C#类来学习如何从powershell脚本调用C#类。我将该项目编译为“类库”并复制到我的C:\驱动器上。

用Google搜索并发现我们需要使用以下命令在powershell中注册.DLL。

 PS C:\WINDOWS\system32> [Reflecion.Assembly]::LoadFile("C:\Calculator.dll")

PS C:\WINDOWS\system32> $ml = new-object Calculator()
       At line:1 char:29
      + $ml = new-object Calculator()
       +                             ~
   An expression was expected after '('.
+ CategoryInfo          : ParserError: (:) [], 
 ParentContainsErrorRecordException
   + FullyQualifiedErrorId : ExpectedExpression

该命令后我没有收到任何错误。 当我尝试访问这样的类时,我得到错误。 PowerShell新手。有什么建议吗?感谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Calculator
{
    public class Calculator
    {
    #region "Private Data Members"

        private int _operandA;
        private int _operandB;

    #endregion "Private Data Members"

        public int OperandA
        {
            get { return _operandA; }
            set { _operandA = value; }
        }     

        public int OperandB
        {
            get { return _operandB; }
            set { _operandB = value; }
        }

        public void AddNumbers(int a, int b)
        {
            int c;
            c = a + b;
            MessageBox.Show("The addition of 2 operands is c");
        } 
    }
}

2 个答案:

答案 0 :(得分:4)

您应该添加-type然后创建新对象。 根据您的C#,您的命名空间是计算器,您需要从该命名空间调用该类,确保在新建对象

中添加另一个计算器
Add-Type -Path 'C:\Calculator'
New-Object Calculator.Calculator

一个工作的例子是

Add-Type -Path 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Management.dll'
$Management = new-object System.Management.Instrumentation.Instrumentation
$Management
  

输出:System.Management.Instrumentation.Instrumentation

答案 1 :(得分:2)

您不需要使用()进行实例化,并且还需要限定您的类定义的命名空间。

PS> [Reflection.Assembly]::LoadFile("C:\Calculator.dll")
PS> $ml = new-object Calculator.Calculator