1: private void invokeSPCmdlet()
2: {
3: // create runspace configuration
4: RunspaceConfiguration config = RunspaceConfiguration.Create();
5:
6: // PSSnapIn exception object
7: PSSnapInException Ex = null;
8:
9: try
10: {
11: //add Microsoft SharePoint PowerShell SnapIn
12: PSSnapInInfo pssnap = config.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out Ex);
13:
14: //create powershell runspace
15: Runspace cmdlet = RunspaceFactory.CreateRunspace(config);
16:
17: cmdlet.Open();
18:
19: RunspaceInvoke scriptInvoker = new RunspaceInvoke(cmdlet);
20:
21: // set powershell execution policy to unrestricted
22: scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
23:
24: // create a pipeline and load it with command object
25: Pipeline pipeline = cmdlet.CreatePipeline();
26:
27: Command cmd = new Command("Get-SPSite"); // Using Get-SPFarm powershell command
28: pipeline.Commands.Add(cmd);
29:
30:
31: pipeline.Commands.Add("Out-String"); // this will format the output
32: IEnumerable<PSObject> output = pipeline.Invoke();
33:
34: pipeline.Stop();
35: cmdlet.Close();
36:
37: // process each object in the output and append to stringbuilder
38: StringBuilder results = new StringBuilder();
39: foreach (PSObject obj in output)
40: {
41: results.AppendLine(obj.ToString());
42: }
43: //set the output to a multi-line text box
44: textBox1.Text = results.ToString();
45: }
46: catch (Exception exError)
47: {
48: MessageBox.Show(exError.Message.ToString());
49: }
50: }
51: