简体   繁体   English

C#如何从字符串导入Powershell模块

[英]c# how to import a powershell module from a string

I'm using c# and I want to use import-module to import a powershell script. 我正在使用c#,并且想使用import-module导入Powershell脚本。 However I don't want to have a .psm1 file on disk. 但是我不想在磁盘上有.psm1文件。 I want to have it hardcoded on my code, like in a string and then import it. 我想将其硬编码在我的代码上,例如在字符串中,然后将其导入。

Is that possible? 那可能吗?

All the example I can find are something like: 我能找到的所有示例都是这样的:

pipeline.Commands.Add("Import-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("Name", @"G:\PowerShell\PowerDbg.psm1")

or something like: 或类似的东西:

var ps = PowerShell.Create(myRS);
ps.Commands.AddCommand("Import-Module").AddArgument(@"g:\...\PowerDbg.psm1")
ps.Invoke()

However as I said above I don't want to read a file from disk. 但是,正如我上面所说,我不想从磁盘读取文件。 I want it hardcoded to avoid multiple files. 我希望对其进行硬编码,以避免出现多个文件。 I want everything on an exe and that's it. 我想要一个exe上的所有内容,仅此而已。 I couldn't find a way, any help is appreciated. 我找不到办法,不胜感激。

The reason I want to use import-module is because after importing the module I want to do something like: 我要使用import-module的原因是,在导入模块后,我想执行以下操作:

get-command -module <whatever>

and get a list of all its functions. 并获取其所有功能的列表。 Any other way to list functions from a script might be helpful too. 从脚本列出功能的任何其他方法也可能会有所帮助。

Thanks. 谢谢。

You're looking for New-Module ; 您在寻找New-Module ; it does exactly what you're asking for. 它完全符合您的要求。

From the TechNet page (paraphrased): 从TechNet页面(解释为):

New-Module -ScriptBlock {
    $SayHelloHelp="Type 'SayHello', a space, and a name."
    function SayHello ($name) { 
        "Hello, $name" 
    } 
    Export-ModuleMember -function SayHello -Variable SayHelloHelp
} -Name PowerDbg

C# Example (not tested): C#示例(未经测试):

string moduleContents = @"...";
pipeline.Commands.Add("New-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("ScriptBlock", moduleContents);
command.Parameters.Add("Name", "PowerDbg");
pipeline.Invoke();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM