【问题标题】:How to reference .NET assemblies using PowerShell如何使用 PowerShell 引用 .NET 程序集
【发布时间】:2011-03-05 23:51:12
【问题描述】:

我是一名 C# .NET 开发人员/架构师,并且了解它使用对象(.NET 对象)而不仅仅是流/文本。

我希望能够使用 PowerShell 调用我的 .NET(C# 库)程序集上的方法。

如何在 PowerShell 中引用程序集并使用该程序集?

【问题讨论】:

    标签: powershell assemblies


    【解决方案1】:

    使用 PowerShell 2.0,您可以使用内置的 Cmdlet Add-Type。

    您只需要指定 dll 的路径。

    Add-Type -Path foo.dll
    

    此外,您可以使用带有 Add-Type 的内联 C# 或 VB.NET。 @" 语法是 HERE 字符串。

    C:\PS>$source = @"
        public class BasicTest
        {
            public static int Add(int a, int b)
            {
                return (a + b);
            }
    
            public int Multiply(int a, int b)
            {
                return (a * b);
            }
        }
        "@
    
        C:\PS> Add-Type -TypeDefinition $source
    
        C:\PS> [BasicTest]::Add(4, 3)
    
        C:\PS> $basicTestObject = New-Object BasicTest 
        C:\PS> $basicTestObject.Multiply(5, 2)
    

    【讨论】:

    • Visual Studio 中该 PowerShell 的几个选项:powerguivsx.codeplex.com PowerShell Plus:IDE powershellplus.com
    • 最新的 ISE 具有智能感知功能。
    • 添加类型:无法添加类型。不支持“.EXE”扩展名。
    • 只需按 Tab 键即可自动完成,习惯于使用|gm 大量操作。不需要 IDE。
    • 我通过将其重命名为 .DLL 来解决“不支持“.EXE”扩展名的问题:P
    【解决方案2】:

    看看博文Load a Custom DLL from PowerShell

    以一个简单的数学库为例。它有一个静态 Sum 方法和一个实例 Product 方法:

    namespace MyMathLib
    {
        public class Methods
        {
            public Methods()
            {
            }
    
            public static int Sum(int a, int b)
            {
                return a + b;
            }
    
            public int Product(int a, int b)
            {
                return a * b;
            }
        }
    }
    

    在 PowerShell 中编译并运行:

    > [Reflection.Assembly]::LoadFile("c:\temp\MyMathLib.dll")
    > [MyMathLib.Methods]::Sum(10, 2)
    
    > $mathInstance = new-object MyMathLib.Methods
    > $mathInstance.Product(10, 2)
    

    【讨论】:

    • 链接正在这里加载。我将更新我的帖子并从中复制相关部分。
    • 感谢您的文字。 :) 我现在知道为什么我在搜索时找不到答案。我会试试看,让你知道我是怎么走的。 :)
    • @Russell:add-type -path .\foo.dll。您也可以使用它直接编译代码。
    • @Johannes,达林基本上是对的。他的解决方案会奏效。但是,如果其他人会来这里(例如来自 google),他会看到他的答案并且不会阅读 cmets。这就是为什么我认为Add-Type 应该有另一个答案。
    • 404 在帖子开头的链接上。
    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 2014-06-09
    • 2023-03-18
    • 2012-01-23
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2010-12-09
    相关资源
    最近更新 更多