2010-11-14 173 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(); 
}