Sometimes you just need something done in powershell. For example, you have a command line program, and you need its output in your c# program. Luckily, C# and powershell work great together. Here is a very simple example. Not much happens. But we execute a simple powershell script, so without further ado here is the script.

raw

Write-Information 'Hello World'

All this does, is write "Hello World" to Powershell's information stream. Powershell has a bunch of streams, but that's a topic for another time. So here we go.

One must reference the library "System.Management.Automation". Which can either be found on Nuget, or:

raw

"C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll"

On your machine, it may be someplace different. For example, not under "3.0"... But whatever, that's what I have.

Now, to run this thing out of C#, all you need is to greate a "Powershell" object. The code below should explain this pretty clearly.

raw

namespace HelloWorld
{
    using System;
    using System.Linq;
    using System.Management.Automation;

    /// <summary>
    /// The program.
    /// </summary>
    public sealed class Program
    {
        /// <summary>
        /// The main.
        /// </summary>
        public static void Main()
        {
            // Create a powershell object
            using (var pshell = PowerShell.Create())
            {
                // Add the script to execute
                pshell.AddScript("Write-Information 'Hello World'");

                // Invoke
                pshell.Invoke();

                // Write the output
                Console.WriteLine(
                    string.Join(
                        Environment.NewLine,
                        pshell.Streams.Information.ReadAll().Select(opt => opt.MessageData)));
            }

            // Hang so we can see this thing worked
            Console.ReadLine();
        }
    }
}

So that's it! Now here, things are done kind of poorly. Powershell can return objects to c# and we can read them out of the return value of "Invoke()", but instead we write to a stream and just read the text.