调用从C#PowerShell函数 [英] Calling Powershell functions from C#

查看:160
本文介绍了调用从C#PowerShell函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在它的多个PowerShell函数一个PS1文件。我需要创建一个静态的DLL读取内存中的所有功能和定义。然后它调用这些功能之一时,用户呼叫该DLL并传递函数名以及该函数的参数。

I have a PS1 file with multiple Powershell functions in it. I need to create a static DLL that reads all the functions and their definitions in memory. It then invokes one of these functions when a user calls the DLL and passes in the function name as well as the parameters for the function.

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

My question is, is it possible to do this. ie call a function that has been read and stored in memory?

由于

推荐答案

有可能的,并且在一个以上的方式。这里可能是最简单的一种。

It is possible and in more than one ways. Here is probably the simplest one.

由于我们的职能是在 MyFunctions.ps1 脚本(只是一个用于此演示):

Given our functions are in the MyFunctions.ps1 script (just one for this demo):

# MyFunctions.ps1 contains one or more functions

function Test-Me($param1, $param2)
{
    "Hello from Test-Me with $param1, $param2"
}

然后使用下面的代码。这是PowerShell的,但它是从字面上翻译到C#(你应该做的):

Then use the code below. It is in PowerShell but it is literally translatable to C# (you should do that):

# 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

这篇关于调用从C#PowerShell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆