Import-Module Powershell command not working with C # api

Import-Module command works fine with Windows PowerShell, but the same command does not work in C # api. I am using this project to execute a powershell script: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

it does many of them, but it does not run the "Import-Module 'c: \ vm \ vm.psd1'" command. I'm trying to import Microsoft modules, but that doesn't work either. How to execute "Import-Module" command using c # api?

Also add-pssnapin 'virtualmachinemanager'

doesn't work either.

+3


source to share


2 answers


Try loading the module like this:

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 creating 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 loaded module

+1


source


Try something like this to download the snapin and execute 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
        }
    }
}

      

+1


source







All Articles