10

I'm creating a PowerShell cmdlets from Visual Studio and I can't find out how to call cmdlets from within my C# file, or if this is even possible? I have no trouble running my cmdlets one by one, but I want to set up a cmdlet to run multiple cmdlets in a sequel.

1

2 Answers 2

14

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?

Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't pipeline.Commands.Add(getProcess); be pipeline.Commands.Add(cmd); - otherwise what looks like a pretty good answer.
Taught me something, anyway! Cheers -
Despite its age this is still a very helpful answer. For those using dotnet core and the CLI, begin with dotnet add package system.management.automation to get those namespaces.
Sorry that's not the core package, for Core you need microsoft.powershell.sdk
This is to run existing PowerShell cmdlets. Is there a way to run a custom cmdlet (implemented in C#) using automation API?
2

You can use CliWrap Package as an alternative to call PowerShell cmdlets from C# besides using Microsoft.PowerShell.SDK and System.Management.Automation.

The benefit of CliWrap Package is you can interact with all external cli not only PowerShell but also Git, NPM, Docker, etc.

For example, you can try this C# code. It will retrieve all Visual Studio processes to the console as if you execute it through command line:

using CliWrap;
using CliWrap.Buffered;

namespace ConsoleApp2
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var dbDailyTasks = await Cli.Wrap("powershell")
                .WithArguments(new string[] { "Get-Process", "-Name", "\"devenv\"" })
                .ExecuteBufferedAsync();

            Console.WriteLine(dbDailyTasks.StandardOutput);
            Console.WriteLine(dbDailyTasks.StandardError);
            Console.ReadLine();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.