as19aux
as19aux

Reputation: 133

Opening Windows Powershell through c#

I'm trying to open Powershell through C# code and ultimately the goal is to also write command lines through c# (without using a powershell skript).

I did some reasearch and came up with this code snippet, but for some reason it just doesn't open Powershell. What do I need to change about the code for Powershell to open?

//Opening Powershell
private void Execute()
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
Process pro = Process.Start(startInfo);
pro.WaitForExit();
Thread.Sleep(3000);
pro.Close();
}

Upvotes: 2

Views: 6478

Answers (1)

Leron
Leron

Reputation: 9886

I've played around with this. Maybe there are some other ways to do it, but this works as well. Since you want some initial setup I think you need to use EnvironmentVariables and if you do that you also need to add

startInfo.UseShellExecute = false;

so one working example would be

    static void Main(string[] args)
    {
        OpenPowerShell(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");
    }

    static void OpenPowerShell(string path)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo(path);
        startInfo.UseShellExecute = false;
        startInfo.EnvironmentVariables.Add("RedirectStandardOutput", "true");
        startInfo.EnvironmentVariables.Add("RedirectStandardError", "true");
        startInfo.EnvironmentVariables.Add("UseShellExecute", "false");
        startInfo.EnvironmentVariables.Add("CreateNoWindow", "true");
        Process.Start(startInfo);
    }

Or if you are OK with another window just:

    static void Main(string[] args)
    {
        OpenPowerShell(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");
    }

    static void OpenPowerShell(string path)
    {
        Process.Start(path);
    }

Upvotes: 1

Related Questions