2010-11-14 122 views
10

我有一個包含多個Powershell函數的PS1文件。我需要創建一個靜態DLL來讀取內存中的所有函數及其定義。然後,當用戶調用DLL並傳入函數名稱以及函數的參數時,它會調用其中一個函數。從C調用Powershell函數#

我的問題是,是否有可能這樣做。即調用已讀取並存儲在內存中的函數?

謝謝

+0

如果你想在.NET Core中執行powershell,請看[https://stackoverflow.com/questions/39141914/running-powershell-from-net-core](https://stackoverflow.com/問題/ 39141914/running-powershell-from-net-core) – Sielu 2018-01-22 10:29:58

回答

4

這是可能的,並在一個以上的方式。這可能是最簡單的一個。

鑑於我們的功能都在MyFunctions.ps1腳本(只有我一個。這個演示):

# MyFunctions.ps1 contains one or more functions 

function Test-Me($param1, $param2) 
{ 
    "Hello from Test-Me with $param1, $param2" 
} 

然後使用下面的代碼。這是PowerShell的,但它是從字面上翻譯到C#(你應該這樣做):

# create the engine 
$ps = [System.Management.Automation.PowerShell]::Create() 

# "dot-source my functions" 
$null = $ps.AddScript(". .\MyFunctions.ps1", $false) 
$ps.Invoke() 

# clear the commands 
$ps.Commands.Clear() 

# call one of that functions 
$null = $ps.AddCommand('Test-Me').AddParameter('param1', 42).AddParameter('param2', 'foo') 
$results = $ps.Invoke() 

# just in case, check for errors 
$ps.Streams.Error 

# process $results (just output in this demo) 
$results 

輸出:

Hello from Test-Me with 42, foo 

對於PowerShell類見的更多細節:

http://msdn.microsoft.com/en-us/library/system.management.automation.powershell

+4

問題是如何在c#中做到這一點,你回答如何在PowerShell中做到這一點,並告訴他自己翻譯成C#?我知道這並不難,但真的嗎? – 2012-05-30 17:59:19

+0

@Eric Brown - Cal - 這是你對這個問題的理解。我的理解不同 - 應該從C#,VB.NET,F#,任何.NET語言中調用PowerShell API方法。 – 2012-05-30 18:39:19

+1

我困惑嗎?是不是「從C#調用Powershell函數」的標題。我錯過了什麼? – 2012-05-30 18:46:34

9

以下是上述代碼的等效C#代碼

string script = "function Test-Me($param1, $param2) { \"Hello from Test-Me with $param1, $param2\" }"; 

using (var powershell = PowerShell.Create()) 
{ 
    powershell.AddScript(script, false); 

    powershell.Invoke(); 

    powershell.Commands.Clear(); 

    powershell.AddCommand("Test-Me").AddParameter("param1", 42).AddParameter("param2", "foo"); 

    var results = powershell.Invoke(); 
}