My Technical Notes

Thursday, 13 July 2017

Calling PowerShell from C#

First add the `System.Management.Automation` package:


Install-Package System.Management.Automation

The following code sample doubles a sequence of integers `1, 2, 3`:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ps = System.Management.Automation.PowerShell.Create())
            {
                var foreachCommand = new System.Management.Automation.Runspaces.Command("ForEach-Object");
                foreachCommand.Parameters.Add("Process", System.Management.Automation.ScriptBlock.Create("$_ * 2"));

                ps.Commands.AddCommand(foreachCommand);

                var result = ps.Invoke(new[] { 1, 2, 3 });
            }
        }
    }
}

No comments: