【发布时间】:2011-03-05 23:51:12
【问题描述】:
我是一名 C# .NET 开发人员/架构师,并且了解它使用对象(.NET 对象)而不仅仅是流/文本。
我希望能够使用 PowerShell 调用我的 .NET(C# 库)程序集上的方法。
如何在 PowerShell 中引用程序集并使用该程序集?
【问题讨论】:
标签: powershell assemblies
我是一名 C# .NET 开发人员/架构师,并且了解它使用对象(.NET 对象)而不仅仅是流/文本。
我希望能够使用 PowerShell 调用我的 .NET(C# 库)程序集上的方法。
如何在 PowerShell 中引用程序集并使用该程序集?
【问题讨论】:
标签: powershell assemblies
使用 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)
【讨论】:
|gm 大量操作。不需要 IDE。
看看博文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)
【讨论】:
add-type -path .\foo.dll。您也可以使用它直接编译代码。
Add-Type 应该有另一个答案。