Skip to content

Instantly share code, notes, and snippets.

@scarmuega
Created December 20, 2011 13:35
Show Gist options
  • Save scarmuega/1501587 to your computer and use it in GitHub Desktop.
Save scarmuega/1501587 to your computer and use it in GitHub Desktop.
Execute PowerShell cmdlet from C#
// First create a runspace
// You really only need to do this once. Each pipeline you create can run in this runspace.
RunspaceConfiguration psConfig = RunspaceConfiguration.Create();
var psRunspace = RunspaceFactory.CreateRunspace(psConfig);
psRunspace.Open();
// Now create a pipeline for the current cmdlet invocation
using ( Pipeline psPipeline = psRunspace.CreatePipeline() )
{
// Define the command to be executed in this pipeline
Command command = new Command( “My-Cmdlet” )
// Add a parameter to this command
command.Parameters.Add( “Parameter1Name”, “Parameter1Value” );
// Add this command to the pipeline
psPipeline.Commands.Add( command );
try
{
// Invoke the cmdlet
var results = psPipeline.Invoke();
// Process the results
}
catch (CmdletInvocationException exception)
{
// Process the exception here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment