当前位置: 首页 > 编程语言 > C#

从C#调用Powershell函数分享

时间:2023-04-10 20:42:41 C#

从C#调用Powershell函数我有一个包含多个Powershell函数的PS1文件。我需要创建一个静态DLL来读取内存中的所有函数及其定义。然后,当用户调用DLL并传入函数名称和函数参数时,它会调用其中一个函数。我的问题是,是否可以这样做。即调用已读取并存储在内存中的函数?谢谢,这是与上述代码等效的C#代码stringscript="functionTest-Me($param1,$param2){"HellofromTest-Mewith$param1,$param2"}";使用(varpowershell=PowerShell.Create()){powershell.AddScript(script,false);powershell.Invoke();powershell.Commands.Clear();powershell.AddCommand("Test-Me").AddParameter("param1",42).AddParameter("param2","foo");varresults=powershell.Invoke();这是可能的,并且有不止一种方法。这可能是最简单的一个。假定我们的函数在MyFunctions.ps1脚本中(此演示仅使用一个):#MyFunctions.ps1包含一个或多个函数functionTest-Me($param1,$param2){"HellofromTest-Mewith$param1,$param2"}然后使用下面的代码。它在PowerShell中,但实际上可以转换为C#(你应该这样做):#创建引擎$ps=[System.Management.Automation.PowerShell]::Create()#"dot-sourcemyfunctions"$null=$ps.AddScript("..MyFunctions.ps1",$false)$ps.Invoke()#清除命令$ps.Commands.Clear()#调用其中一个函数$null=$ps.AddCommand('Test-Me').AddParameter('param1',42).AddParameter('param2','foo')$results=$ps.Invoke()#为了以防万一,检查错误$ps.Streams.Error#process$结果(仅在此演示中输出)$results输出:来自Test-Me的Hellowith42,foo有关PowerShell类的更多详细信息,请参阅:http://msdn.microsoft.com/en-us/library/system.management。automation.powershell以上就是C#学习教程:从C#调用Powershell函数全部内容分享给大家。如果对你有用,需要了解更多C#学习教程,希望大家多多关注——本文来自网络收藏,不代表立场,如涉及侵权,请点击有权联系管理员删除。如需转载请注明出处: