Feb 26, 2014

Programmatically talking to powershell using c#

Recently i had to address a requirement where I need to talk to sharepoint management shell and get the output onto the web page using c#.

You need to refer the below two references to achieve this:
using System.Management.Automation.Runspaces;
using System.Management.Automation;

below is the required snippet:
private static string GetDetails()

        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException OExSnapIn = null;

           PSSnapInInfo pssnap = config.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out OExSnapIn);

            //create powershell runspace
          Runspace cmdlet = RunspaceFactory.CreateRunspace(config);

            cmdlet.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(cmdlet);

            // set powershell execution policy to unrestricted

            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            // create a pipeline and load it with command object

            Pipeline pipeline = cmdlet.CreatePipeline();

            Command cmd = new Command("Get-SPFarm");

            pipeline.Commands.Add(cmd);

            pipeline.Commands.Add("Out-String");
          // this will format the output

            IEnumerable output = pipeline.Invoke();
          pipeline.Stop();

            cmdlet.Close();
           // process each object in the output and append to stringbuilder 

            StringBuilder results = new StringBuilder();
          foreach (PSObject obj in output)
          {
               results.AppendLine(obj.ToString());
           }
           return results.ToString();

        }
Hope this helps!!

 I have implemented a forms solution like below.


 

No comments: