Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run powershell commands in C#

RunspaceConfiguration psConfig = RunspaceConfiguration.Create();
Runspace psRunspace = RunspaceFactory.CreateRunspace(psConfig);
psRunspace.Open();
using (Pipeline psPipeline = psRunspace.CreatePipeline())
            {

            // Define the command to be executed in this pipeline
            Command command = new Command("Add-spsolution");

            // Add a parameter to this command
            command.Parameters.Add("literalpath", @"c:\project3.wsp");

            // Add this command to the pipeline 
            psPipeline.Commands.Add(command);


                // Invoke the cmdlet
            try
            {
                Collection<PSObject> results = psPipeline.Invoke();
                Label1.Text = "hi"+results.ToString();
                // Process the results
            }
            catch (Exception exception)
            {
                Label1.Text = exception.ToString();// Process the exception here
            }

        }

It is throwing the exception:

System.Management.Automation.CommandNotFoundException: The term 'add-spsolution' is not recognized as the name of a cmdlet, function, script file, or operable program.

Any suggestions why?

like image 271
Ramnik Avatar asked Jun 12 '10 08:06

Ramnik


People also ask

How do I Run a PowerShell command?

To run a script, open a PowerShell window, type the script's name (with or without the . ps1 extension) followed by the script's parameters (if any), and press Enter.

Can I Run C program in PowerShell?

Specifying a path: You must tell the console where it is if the program is located somewhere else. To do so, specify the absolute or relative path name of the program. The "&" changes string into commands: PowerShell doesn't treat text in quotes as a command. Prefix a string with "&" to actually execute it.

Can I Run PowerShell command from CMD?

You need to write the keyword “powershell” with a “-file” parameter followed by the path of the script to run the PowerShell script from CMD.


1 Answers

Add this command first:

Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0

like image 146
Ruslan Avatar answered Sep 18 '22 14:09

Ruslan