Baris
Baris

Reputation: 455

Powershell Import-Module command doesn't work with c# api

Import-Module command work fine with powershell windows console but same command doesn't work on c# api. i'm using this project for execute powershell script: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

it execute many of them commands but it doesn't execute "Import-Module 'c:\vm\vm.psd1'" command. i try import microsoft modules but it doesn't work too. How can i execute "Import-Module" command with c# api?

Also add-pssnapin 'virtualmachinemanager' doesn't work too.

Upvotes: 3

Views: 4775

Answers (2)

jmrnet
jmrnet

Reputation: 548

Try something like this for loading the snapin and executing your commands:

using System.Management.Automation.Runspaces;

//...

var rsConfig = RunspaceConfiguration.Create();
using (var myRunSpace = RunspaceFactory.CreateRunspace(rsConfig))
{
    PSSnapInException snapInException = null;
    var info = rsConfig.AddPSSnapIn("FULL.SNAPIN.NAME.HERE", out snapInException);

    myRunSpace.Open();
    using (var pipeLine = myRunSpace.CreatePipeline())
    {
        Command cmd = new Command("YOURCOMMAND");
        cmd.Parameters.Add("PARAM1", param1);
        cmd.Parameters.Add("PARAM2", param2);
        cmd.Parameters.Add("PARAM3", param3);

        pipeLine.Commands.Add(cmd);
        pipeLine.Invoke();
        if (pipeLine.Error != null && pipeLine.Error.Count > 0)
        {
            //check error
        }
    }
}

Upvotes: 1

CB.
CB.

Reputation: 60976

Try load module in this way:

PowerShell powershell = PowerShell.Create();
powerShell.Commands.AddCommand("Import-Module").AddParameter("Name", "c:\vm\vm.psd1'");

or

PowerShell powershell = PowerShell.Create();
powershell.Commands.AddCommand("Add-PsSnapIn").AddParameter("Name", "virtualmachinemanager");

With a pipeline try create an InitialSessionState

InitialSessionState iss = InitialSessionState.CreateDefault();
           iss.ImportPSModule(new string[] { @"C:\vm\vm.psd1"});
           Runspace runSpace = RunspaceFactory.CreateRunspace(iss);
           runSpace.Open();

then use your code with pipeline to run cmdlet from module loaded

Upvotes: 1

Related Questions