Last active
January 17, 2018 21:46
-
-
Save cpoDesign/66187c14092ceb559250183abbf9e774 to your computer and use it in GitHub Desktop.
Example how to run powershell in .net 4.7 from C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Web.Controllers | |
{ | |
public class PSExecution | |
{ | |
public PSCommand PSCommand{get;set;} | |
public string Output{get; private set;} | |
public void SetOutput(string output){ | |
this.Output = output; | |
} | |
} | |
public class PSCommand | |
{ | |
public string Text{get;set;} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Depends on nuget package: | |
<package id="System.Management.Automation" version="6.1.7601.17515" targetFramework="net47" /> | |
*/ | |
using System.Collections.ObjectModel; | |
using System.Management.Automation; | |
using System.Management.Automation.Runspaces; | |
using System.Text; | |
namespace Web.Controllers | |
{ | |
public class PS | |
{ | |
/// <summary> | |
/// Runs the script. | |
/// </summary> | |
/// <param name="scriptText">The script text.</param> | |
/// <returns>string from output</returns> | |
public PSExecution RunScript(PSExecution psExecution) | |
{ | |
// create Powershell runspace | |
Runspace runspace = RunspaceFactory.CreateRunspace(); | |
// open it | |
runspace.Open(); | |
// create a pipeline and feed it the script text | |
Pipeline pipeline = runspace.CreatePipeline(); | |
pipeline.Commands.AddScript(psExecution.PSCommand.Text); | |
// add an extra command to transform the script | |
// output objects into nicely formatted strings | |
// "Get-Process" returns a collection | |
// of System.Diagnostics.Process instances. | |
pipeline.Commands.Add("Out-String"); | |
// execute the script | |
Collection<PSObject> results = pipeline.Invoke(); | |
// close the runspace | |
runspace.Close(); | |
// convert the script result into a single string | |
StringBuilder stringBuilder = new StringBuilder(); | |
foreach (PSObject obj in results) | |
{ | |
stringBuilder.AppendLine(obj.ToString()); | |
} | |
psExecution.SetOutput(stringBuilder.ToString()); | |
return psExecution; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment