Created
December 20, 2011 13:35
-
-
Save scarmuega/1501587 to your computer and use it in GitHub Desktop.
Execute PowerShell cmdlet from C#
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
| // 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