C#: Run Powershell Script from C# .NET Core

5/11/2020 8:11:43 PM
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1
{
    public class Powershell
    {
        static string _Script_Path = @"C:\My Projects\Tasks To Run\task-01.ps1\";        


        public static void Test_Task_01()
        {           
            //requires Nuget Packages:
            //Microsoft.Powershell.SDK
            //System.Management.Automation
            using (var ps = System.Management.Automation.PowerShell.Create())
            {
                var results = ps.AddScript(_Script_Path).Invoke();
                if (results != null)
                {
                    output += results.ToString();
                }
            }          
        }


        public static void Test_Task_02()
        {            
            var startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = "powershell.exe";

            startInfo.Arguments = "\"& \"\"" + _Script_Path + "\"\"\"";

            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = !startInfo.UseShellExecute;
            startInfo.RedirectStandardError = !startInfo.UseShellExecute;


            //startInfo.CreateNoWindow = true;
            var process = new System.Diagnostics.Process();
            process.StartInfo = startInfo;
            process.Start();


            string output = "";
            if (startInfo.RedirectStandardOutput)
            {
                output += "Standard Output";
                output += Environment.NewLine;
                output += process.StandardOutput.ReadToEnd();
            }


            if (startInfo.RedirectStandardError)
            {
                var error = process.StandardError.ReadToEnd();
                if (!string.IsNullOrWhiteSpace(error))
                {
                    if (!string.IsNullOrWhiteSpace(output))
                    {
                        output += Environment.NewLine;
                        output += Environment.NewLine;
                    }
                    output += "Error Output";
                    output += Environment.NewLine;
                    output += error;
                }
            }


            Console.WriteLine(output);
        }
    }
}