从C#调用Powershell函数

Sea*_*ean 12 c# powershell cmdlets

我有一个PS1文件,其中包含多个Powershell函数.我需要创建一个静态DLL,读取内存中的所有函数及其定义.然后,当用户调用DLL并传入函数名称以及函数的参数时,它会调用其中一个函数.

我的问题是,是否可以这样做.即调用已读取并存储在内存中的函数?

谢谢

Amr*_*eda 14

这是上面提到的代码的等效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();
}
Run Code Online (Sandbox Code Playgroud)


Rom*_*min 5

这可能并且不止一种方式.这可能是最简单的一个.

鉴于我们的功能在MyFunctions.ps1脚本中(只有一个用于此演示):

# MyFunctions.ps1 contains one or more functions

function Test-Me($param1, $param2)
{
    "Hello from Test-Me with $param1, $param2"
}
Run Code Online (Sandbox Code Playgroud)

然后使用下面的代码.它在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
Run Code Online (Sandbox Code Playgroud)

输出:

Hello from Test-Me with 42, foo
Run Code Online (Sandbox Code Playgroud)

有关PowerShell课程的更多详细信息,请参阅:

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

  • 问题是如何在c#中做到这一点,你回答如何在powershell中做到这一点,并告诉他将自己翻译成c#?我知道这不是很难,但真的吗? (7认同)
  • 我很困惑吗?标题不是"从C#调用Powershell函数".我错过了什么? (4认同)