在C#中运行powershell命令

时间:2010-06-12 08:05:48

标签: sharepoint powershell

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
            }

        }

抛出异常:

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

有什么建议吗?

4 个答案:

答案 0 :(得分:10)

首先添加此命令:

Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0

答案 1 :(得分:8)

您必须使用import-module命令为sharepoint加载正确的模块。使用get-module查找可用模块。

要以编程方式执行此操作,请参阅我关于该主题的帖子:

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

-Oisin

答案 2 :(得分:2)

我最近有这个问题。就我而言,我既没有看到添加的解决方案也无法添加解决方案。首先,我使用PowerShell命令下面删除解决方案:

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

然后我就可以添加新的代码解决方案了。

答案 3 :(得分:-1)

还要确保从运行在IIS上的Web应用程序运行“Add-SPSolution”命令,而不是使用标准Visual Studio服务器(当您按F5时)。