如果管理Windows Server的Developer或是SE/SP剛好也略懂C#,來試試在Powershell裡頭寫C#。
有兩種方式:
- 把C#方法寫入Powershell中
- 從Powershell呼叫C# dll或exe:
把C#方法寫入Powershell中:
先將C#方法寫成字串,再用Add-Type增加定義,最後New起來執行。
$Math = @"
public class Calc
{
public int Add(int a,int b)
{
return a+b;
}
public int Mul(int a,int b)
{
return a*b;
}
}
"@
Add-Type -TypeDefinition $Math
$CalcClassInstance = New-Object -TypeName Calc
$CalcClassInstance.Add(2,3)
$CalcClassInstance.Mul(2,3)
執行結果: 成功!
撰寫程式時還有Intellisense
從Powershell呼叫C# dll或exe:
C# Project and Code
namespace utEntity.Powershell
{
public class Calc
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Mul(int a, int b)
{
return a * b;
}
}
}
注意namespace、注意static
編譯成功後將dll放置在指定目錄,這邊我們假設放在C:\Temp\powershell\
Powershell Code
Get-ChildItem -recurse "c:\temp\powershell\"|
Where-Object {($_.Extension -EQ ".dll") -or ($_.Extension -eq ".exe")} |
ForEach-Object { $AssemblyName=$_.FullName; Try {[Reflection.Assembly]::LoadFile($AssemblyName)} Catch{ "***ERROR*** Not .NET assembly: " + $AssemblyName}}
[utEntity.Powershell.Calc]::Add(2,3)
[utEntity.Powershell.Calc]::Mul(2,3)
打開Powershell ISE,把上面的powershell指令碼貼進來
執行成功!
2+3=5; 2*3=6
如果是"非靜態方法"呼叫,要先new object(instance)
$Class= New-Object "C.Biz.ISBRPT001"
小結:
- Powershell can do EVERYTHING!
- C#市占率越來越高。
參考:
Calling C# code in Powershell and vice versa
Using Powershell and Reflection API to invoke methods from .NET Assemblies