How to call PowerShell cmdlets from C # in Visual Studio

I'm creating PowerShell cmdlets from Visual Studio and I can't seem to figure out how to call the cmdlets from my C # file, or if that's possible? I have no problem running my cmdlets one by one, but I want to configure the cmdlet to run multiple cmdlets in the sequel.

+2


source to share


1 answer


Yes, you can call cmdlets from your C # code.

You will need these two namespaces:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

      

Open the gap:

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 your pipeline:

pipeline.Commands.Add(cmd);

      

Run command (s):

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
   ....do stuff with psObject (output to console, etc)
}

      

Does this answer your question?

+7


source







All Articles