Skip to content

Instantly share code, notes, and snippets.

@vbjay
Created January 16, 2019 22:21
Show Gist options
  • Save vbjay/6aa9baaa7bf17dcc7ae1e6c09a0a3141 to your computer and use it in GitHub Desktop.
Save vbjay/6aa9baaa7bf17dcc7ae1e6c09a0a3141 to your computer and use it in GitHub Desktop.
Sample code to run powershell in c# and generate json of the objects returned
<Query Kind="Program">
<Reference>&lt;ProgramFilesX86&gt;\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll</Reference>
<Namespace>Microsoft.VisualBasic</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>System.Management.Automation.Runspaces</Namespace>
<Namespace>System.Collections.ObjectModel</Namespace>
<Namespace>System.Management.Automation</Namespace>
</Query>
void Main()
{
RunScript("Get-Process").Dump();
}
// Define other methods and classes here
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
Runspace.DefaultRunspace = runspace;
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("ConvertTo-Json");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
//results.Dump();
var finalResults = string.Join(Environment.NewLine, results);
// close the runspace
runspace.Close();
Runspace.DefaultRunspace = null;
// convert the script result into a single string
return finalResults;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment