[英]Calling Powershell functions from C#
我有一个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
类的更多详细信息,请参阅:
http://msdn.microsoft.com/en-us/library/system.management.automation.powershell
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.