How to call PowerShell cmdlets from C# in Visual Studio
Yes, you can call cmdlets from your C# code.
You'll need these two namespaces:
using System.Management.Automation;using System.Management.Automation.Runspaces;
Open a runspace:
Runspace runSpace = RunspaceFactory.CreateRunspace();runSpace.Open();
Create a pipeline:
Pipeline pipeline = runSpace.CreatePipeline();
Create a command:
Command cmd= new Command("APowerShellCommand");
You can add parameters:
cmd.Parameters.Add("Property", "value");
Add it to the pipeline:
pipeline.Commands.Add(cmd);
Run the command(s):
Collection output = pipeline.Invoke();foreach (PSObject psObject in output){ ....do stuff with psObject (output to console, etc)}
Does this answer your question?