简体   繁体   English

从C#调用Powershell函数

[英]Calling Powershell functions from C#

I have a PS1 file with multiple Powershell functions in it. 我有一个PS1文件,其中包含多个Powershell函数。 I need to create a static DLL that reads all the functions and their definitions in memory. 我需要创建一个静态DLL,读取内存中的所有函数及其定义。 It then invokes one of these functions when a user calls the DLL and passes in the function name as well as the parameters for the function. 然后,当用户调用DLL并传入函数名称以及函数的参数时,它会调用其中一个函数。

My question is, is it possible to do this. 我的问题是,是否可以这样做。 ie call a function that has been read and stored in memory? 即调用已读取并存储在内存中的函数?

Thanks 谢谢

Here's the equivalent C# code for the code mentioned above 这是上面提到的代码的等效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();
}

It is possible and in more than one ways. 这可能并且不止一种方式。 Here is probably the simplest one. 这可能是最简单的一个。

Given our functions are in the MyFunctions.ps1 script (just one for this demo): 鉴于我们的函数在MyFunctions.ps1脚本中(这个演示只有一个):

# MyFunctions.ps1 contains one or more functions

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

Then use the code below. 然后使用下面的代码。 It is in PowerShell but it is literally translatable to C# (you should do that): 它在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

Output: 输出:

Hello from Test-Me with 42, foo

For more details of the PowerShell class see: 有关PowerShell类的更多详细信息,请参阅:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM