Csharp/C#教程:从C#调用Powershell函数分享


从C#调用Powershell函数

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

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

谢谢

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

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

鉴于我们的函数在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类的更多详细信息,请参阅:

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

上述就是C#学习教程:从C#调用Powershell函数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1269681.html

(0)
上一篇 2022年11月22日
下一篇 2022年11月22日

精彩推荐