ineffablep
Contributor
Contributor

Open PowerCli from C# and run Commands on PowerCli

Hi,

I want to run commands in PowerCli in remote server from C#,

So I need to open PowerCli in remote server from C#  

I tried to run the below command but getting Connect-VIServer is not found as a cdmlt command.

Please provide me the C# code to open PowerCli and run Connect on that Runspace.

Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84

Code I used to run the command

InitialSessionState initial = InitialSessionState

.CreateDefault();

initial.ImportPSModule(

new[] {"abc"

});

// create Powershell runspace

Runspace runspace = RunspaceFactory

.CreateRunspace(initial);

// open it

runspace.Open();

// create a pipeline and feed it the script text

Pipeline

pipeline = runspace.CreatePipeline();

// Create Command to Set Na Option

var access = new Command ("Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84");

// Add Command to Pipeline

pipeline.Commands.Add(access);

//Execute by invoking

pipeline.Invoke();

// close the runspace

runspace.Close();

}

0 Kudos
9 Replies
ykalchev
VMware Employee
VMware Employee

Hi,

All you need to add in you snippet is to import PowerCLI snapin to the runspace:

// create Powershell runspace
RunspaceConfiguration config = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(config);
// open it
runspace.Open();
try {
    // import PowerCLI ViCore snapin

    PSSnapInException warning;
    config.AddPSSnapIn("VMware.VimAutomation.Core", out warning);
    if (warning != null) {
        throw warning;
    }
    // create a pipeline and feed it the script text
    Pipeline pipeline = runspace.CreatePipeline();
    // Create Command to Set Na Option

    var access = new Command ("Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84");

    // Add Command to Pipeline
    pipeline.Commands.Add(access);
    //Execute by invoking
    pipeline.Invoke();        
}finally {
    runspace.Close();
}

Regards,

Yasen

Yasen Kalchev, vSM Dev Team
0 Kudos
ineffablep
Contributor
Contributor

Hi  Yasen,

Thank you very much for the answer, it resolved the issue but I need to import module

Which I have done while creating Runspace but now how  can I import Module.

// Imprt Requrie Modules

InitialSessionState initial = InitialSessionState.CreateDefault();

initial.ImportPSModule(

new[] { "dtap" });

Runspace runspace = RunspaceFactory.CreateRunspace(initial);

Thanks

Sireesh

0 Kudos
ykalchev
VMware Employee
VMware Employee

You can try calling  InitialSessionState.ImportPSSnapIn method after module import:

PSSnapInException warning;

InitialSessionState initial = InitialSessionState.CreateDefault();

initial.ImportPSModule(new[] { "dtap" });

initial.ImportPSSnapIn("VMware.VimAutomation.Core", out warning);

Yasen Kalchev, vSM Dev Team
0 Kudos
madhanSakthi
Contributor
Contributor

HI,

I have used your code and tried to connect to the vsphere server.

But the pipeline.Invoke(); statement throws an exception saying

System.Management.Automation.CommandNotFoundException was unhandled

  Message=The term 'Connect-VIServer -Server 172.17.21.51 -Protocol https -User vmuser -Password pass' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

  Source=System.Management.Automation

  WasThrownFromThrowStatement=false

  CommandName=Connect-VIServer -Server 172.17.21.51 -Protocol https -User vmuser -Password pass

  StackTrace:

       at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandOrigin commandOrigin)

       at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)

       at System.Management.Automation.CommandFactory._CreateCommand(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)

       at System.Management.Automation.Runspaces.Command.CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, Boolean addToHistory)

       at System.Management.Automation.Runspaces.LocalPipeline.CreatePipelineProcessor()

       at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()

       at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()

  InnerException:

Is there any prerequisite to run these powercli commands? Please help me to resolve this error.

0 Kudos
knikolov
VMware Employee
VMware Employee

Which version of PowerCLI are you using? Since the latest version of PowerCLI (6.0R1) all snap-ins were converted to modules and you should import them with ImportPSModule instead of ImportPSSnapIn.

0 Kudos
madhanSakthi
Contributor
Contributor

hi,

Im using Powercli 5.5 R1, The "config.AddPSSnapIn("VMware.VimAutomation.Core", out warning);" in the mentioned code

is working fine without any exceptions. only the invoke command fails.

Is "importPSSnapin" is also required before doing the "AddPSSnapin" ?

Thanks.

0 Kudos
knikolov
VMware Employee
VMware Employee

I think I figured it out. Try changing

var access = new Command ("Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84"); to

var access = new Command ("Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84", true);

It seems like the default constructor does not take complete command with parameters, so you should either specify that or doing it like this

var access = new Command ("Connect-VIServer);

access.Parameters.Add("Server","192.168.10.10");

access.Parameters.Add("Protocol","http"); etc.

Kamen

0 Kudos
udayasenthil
Contributor
Contributor

I am also having the same issue, getting (An exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll but was not handled in user code)error message when i try to run the below mentioned code.

           InitialSessionState iss = InitialSessionState.CreateDefault();

           iss.ImportPSModule(new string[] { "VMware.VimAutomation.Cis.Core" });

           Runspace runSpace = RunspaceFactory.CreateRunspace(iss);

           runSpace.Open();

           Pipeline pipeLine = runSpace.CreatePipeline();

           var connectVI = new Command ("Connect-VIServer");

           connectVI.Parameters.Add("Server", "192.168.90.89");

           connectVI.Parameters.Add("Protocol", "http");

           connectVI.Parameters.Add("User", "vmuser");

           connectVI.Parameters.Add("Password", "**********");

           pipeLine.Commands.Add(connectVI);

           pipeLine.Commands.Add("Out-String");

           Collection<PSObject> resultObjects = pipeLine.Invoke();

           runSpace.Close();

An exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll but was not handled in user code

Additional information: The term 'Connect-VIServer' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Any help in resolving this issue is highly appreciated.

0 Kudos
ejji09
Contributor
Contributor

Hi,

Am using the following code to Open PowerCli from C# and run commands on PowerCli through a button click.. after clicking the button in the debugger output am getting "The thread 0x104c has exited with code 259 (0x103)." which means my code was not succesfull .
i dont know whats going wrong in my code can you please suggest me whats wrong am doing in my code?

private void Powercli_Click(object sender, EventArgs e)

        {

            RunspaceConfiguration config = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(config);

            // open it

            runspace.Open();

            try

            {

                // import PowerCLI ViCore snapin

                PSSnapInException warning;

                config.AddPSSnapIn("VMware.VimAutomation.Core", out warning);

                if (warning != null)

                {

                    throw warning;

                }

                // create a pipeline and feed it the script text

                Pipeline pipeline = runspace.CreatePipeline();

                // Create Command to Set Na Option

                var access = new Command("Connect-VIServer");

                access.Parameters.Add("Server", "192.168.123.108");

                access.Parameters.Add("Protocol", "https");

                access.Parameters.Add("User", "root");

                access.Parameters.Add("Password", "assign");

              // Add Command to Pipeline 

                pipeline.Commands.Add(access);

                //Execute by invoking

                pipeline.Invoke();

            }

            finally

            {

                runspace.Close();

            }

        }

0 Kudos