从C#调用Powershell函数

17

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

我的问题是,是否可以实现这一点?即调用在内存中已经读取和存储的函数?

谢谢。


如果您想在.NET Core中执行PowerShell,请查看https://dev59.com/YlkT5IYBdhLWcg3wB7XP。 - Sielu
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();
}

我尝试实现这个,但遇到了问题。我正在使用WinUI 3。我在这里发布了一个关于它的单独问题,附带详细信息:https://stackoverflow.com/questions/70843636/how-to-call-powershell-functions-from-c-sharp-in-winui-3 - Michael Kintscher they-them

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/zh-cn/library/system.management.automation.powershell


9
问题是如何在C#中实现,而你回答如何在PowerShell中实现,并告诉他自己将其翻译成C#?我知道这不是很难,但是真的吗? - Eric Brown - Cal
@Eric Brown - Cal - 这是你对问题的理解。我的理解不同 - 应该从C#,VB.NET,F#或任何.NET语言中调用哪些PowerShell API方法。 - Roman Kuzmin
6
我应该翻译成:我是否感到困惑?标题不是“从C#调用PowerShell函数”吗?我有什么遗漏吗? - Eric Brown - Cal
1
这是标题中的一个问题吗?问题是:“我的问题是,是否可能做到这一点。即调用已经被读取并存储在内存中的函数?” - Roman Kuzmin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接