17

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

我的问题是,是否有可能做到这一点。即调用已读取并存储在内存中的函数?

谢谢

4

2 回答 2

19

这是上述代码的等效 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();
}
于 2014-04-22T11:13:03.013 回答
5

这是可能的,而且方式不止一种。这里可能是最简单的一个。

鉴于我们的函数在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

于 2010-11-15T07:57:53.410 回答