2

I'm using c# and I want to use import-module to import a powershell script. However I don't want to have a .psm1 file on disk. 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. 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:

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.

2
  • 1
    Somewhat related - check out PSExt for WinDbg if you're looking at automating WinDbg Commented May 23, 2016 at 19:08
  • Sorry the PowerDbg was only a random example I copy pasted from another post. Thanks anyway. Commented May 23, 2016 at 19:45

1 Answer 1

5

You're looking for New-Module; it does exactly what you're asking for.

From the TechNet page (paraphrased):

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):

string moduleContents = @"...";
pipeline.Commands.Add("New-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("ScriptBlock", moduleContents);
command.Parameters.Add("Name", "PowerDbg");
pipeline.Invoke();
Sign up to request clarification or add additional context in comments.

1 Comment

great! the c# example doesn't work but I'll work around it. New-Module seems to be exactly what I need. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.