doorman
doorman

Reputation: 16939

PowerShell not targeting 4.6

I am trying to run a PowerShell script inside C# using .NET 4.6 I have tried to install the PowerShell NuGet but it doesn´t target .NET 4.6 Is there another way I could execute the PowerShell script?

I needed to specify powershell.exe to be able to run the script. But now I have another problem the PowerShell window closes immediately so I am not able to see the error message. I am using the following command

var s = Process.Start(@"Powershell.exe", $@"-noexit  -ExecutionPolicy Bypass -file ""MyScript.ps1; MyFunction"" ""{arguments}""");
s.WaitForExit();

Upvotes: 0

Views: 89

Answers (1)

Mindaugas Bernatavičius
Mindaugas Bernatavičius

Reputation: 3909

Yes, you can run it as you run any external program. System.Diagnostics.Process will help you out.

Here is a code example from Microsoft community:

using System.Diagnostics;

namespace ConsoleApplication2
{
 class Program
 {
  static void Main(string[] args)
  {
   Process myProcess = new Process();

   myProcess.StartInfo.FileName = @"ConsoleApplication1.exe";
   myProcess.StartInfo.UseShellExecute = false;
   myProcess.StartInfo.RedirectStandardOutput = true;
   myProcess.StartInfo.RedirectStandardInput = true;

   myProcess.Start();

   string redirectedOutput=string.Empty;
   while ((redirectedOutput += (char)myProcess.StandardOutput.Read()) != "Enter File Name:") ;

   myProcess.StandardInput.WriteLine("passedFileName.txt");

   myProcess.WaitForExit();

   //verifying that the job was successfull or not?!
   Process.Start("explorer.exe", "passedFileName.txt");
  }
 }
}

ConsoleApplication1.exe should be replaced with YourApplication.ps1

Why would you ever use System.Diagnostics.Process rather than System.Management.Automation which is recommended? Because powershell is slow and if you ever need to replace it, using System.Diagnostics.Process will allow doing it immediately.

Upvotes: 1

Related Questions