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
var output = "";
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()
{
ProcessStartInfo process_start_info = new ProcessStartInfo();
process_start_info.FileName = "powershell.exe";
process_start_info.Arguments = "\"& \"\"" + _Script_Path + "\"\"\"";
Process process = new Process();
process.StartInfo = process_start_info;
process.Start();
process.WaitForExit();
}
public static void Test_Task_03()
{
var startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.Arguments = "\"& \"\"" + _Script_Path + "\"\"\"";
startInfo.UseShellExecute = false;
//WARNING!!! If the powershell script outputs lots of data, this code could hang
//You will need to output using a stream reader and purge the contents from time to time
startInfo.RedirectStandardOutput = !startInfo.UseShellExecute;
startInfo.RedirectStandardError = !startInfo.UseShellExecute;
//startInfo.CreateNoWindow = true;
var process = new System.Diagnostics.Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//if you want to limit how long you wait for the program to complete
//input is in milliseconds
//var seconds_to_wait_for_exit = 120;
//process.WaitForExit(seconds_to_wait_for_exit * 1000);
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);
}
}
}