因为Windows PowerShell能完全访问.NET Framework,所以我们就可以想象如何用Powershell来调用DLL类库呢。
这里我们用C#写一段代码编译为DLL文件(这是在做一个数字大小的比较,CompareI是用静态方法,CompareII则是一般方法)
编译命令:csc /target:library G:/Math2.cs
- namespace Math
- {
- public class Methods
- {
- public Methods()
- {
- }
- public static int CompareI(int a, int b)
- {
- if (a>b)
- return a;
- else
- return b;
- }
- public int CompareII(int a, int b)
- {
- if (a>b)
- return a;
- else
- return b;
- }
- }
- }
最后我们开始在Powershell环境下调用:
- [void][reflection.assembly]::LoadFile("G:/Math2.dll")
- [Math.methods]::CompareI(10,2)
- $a=New-Object Math.Methods
- $a.CompareII(2,3)
结果为:10 3
[void][reflection.assembly]::LoadFile("D:/VS2008/VC/Math2.dll")
我们必须以这种形式加载DLL库
[Math.methods]::CompareI(10,2)
我们看到Powershell在调用静态方法的时候必须使用方括号加上双冒号“::”的形式来调用静态方法。
$a=New-Object Math.Methods
$a.CompareII(2,3)
而一般方法则不然,必须用New-Object来声明一个对象引用。