Thursday, April 7, 2016

Run powershell commands in C#

Leave a Comment
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?

4 Answers

Answers 1

You must use the import-module command to load the correct module for sharepoint. Use get-module to find available modules.

To do this programmatically, see my post on the subject:

http://www.nivot.org/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule.aspx

-Oisin

Answers 2

Add this command first:

Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0

Answers 3

I have this issue recently. In my case I was neither able to see the added solution nor able to add solution. So first I remove solution using below PowerShell Command:

(Get-SPSolution -Identity "YourSolution.wsp").Delete() 

Then I was able to add my new code solution.

Answers 4

Also make sure you are runing "Add-SPSolution" command from Web Applications, which is running on IIS, and NOT with standard Visual Studio server (when you press F5).

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment