Created
January 22, 2019 21:49
-
-
Save TheWover/bd7e580b3cb10ab5447b4dc83013cc88 to your computer and use it in GitHub Desktop.
Runs PowerShell from C# through System.Management.Automation
This file contains hidden or 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
using System; | |
using System.Management.Automation; | |
using System.Collections.ObjectModel; | |
static void Main(string[] args) | |
{ | |
//Using this class: https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=powershellsdk-1.1.0 | |
using (PowerShell PowerShellInstance = PowerShell.Create()) | |
{ | |
PowerShellInstance.AddScript("line 1"); | |
PowerShellInstance.AddScript("line 12"); | |
PowerShellInstance.AddScript("line n"); | |
//Run command provided by user | |
PowerShellInstance.AddScript(args[0]); | |
//Used | |
Collection <PSObject> PSOutput; | |
// invoke execution on the pipeline (collecting output) | |
PSOutput = PowerShellInstance.Invoke(); | |
// loop through each output object item | |
foreach (PSObject outputItem in PSOutput) | |
{ | |
// if null object was dumped to the pipeline during the script then a null | |
// object may be present here. check for null to prevent potential NRE. | |
if (outputItem != null) | |
{ | |
//TODO: do something with the output item | |
// outputItem.BaseOBject | |
Console.WriteLine(outputItem); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment