简体   繁体   中英

Issuing Powershell commands to console from C#

I am unable to send commands to the powershell console after I open it with a C# application. I have also tried other ways which I have commented out at the bottom of my code to show you what I have tried. Here is my code that I using below:

Using System;
Using System.Windows.Forms;
Using System.Management.Automation;

System.Diagnostics.Process CMDprocess = new System.Diagnostics.Process();
var StartProcessInfo = new System.Diagnostics.ProcessStartInfo();
StartProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowershell\v1.0\powershell.exe";
StartProcessInfo.Verb = "runas";

CMDprocess.StartInfo = StartProcessInfo;

CMDprocess.Start();

StartProcessInfo.Arguments = @"C:\Users\user\Desktop\Test.ps1";

CMDprocess.WaitForExit();

//Console.WriteLine("@C:\\Users\\User\\Desktop\\Test.ps1");
//StreamWriter SW = CMDprocess.StandardInput;
//StreamReader SR = CMDprocess.StandardOutput;
//SW.WriteLine(@"C:\Users\User\Desktop\Test.ps1");                
//StartProcessInfo.Arguments = @".\Test.ps1";
//System.Diagnostics.Process.Start(StartProcessInfo);

@ChrisDent suggested a good solution.

However, the only error with you code is, that you have to set the StartInfo before starting the powershell. Try this:

System.Diagnostics.Process CMDprocess = new System.Diagnostics.Process();
var StartProcessInfo = new System.Diagnostics.ProcessStartInfo();
StartProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowershell\v1.0\powershell.exe";
StartProcessInfo.Verb = "runas";
StartProcessInfo.Arguments = @"C:\Users\user\Desktop\Test.ps1";

CMDprocess.StartInfo = StartProcessInfo;
CMDprocess.Start();           
CMDprocess.WaitForExit();

Why not interact directly with PowerShell?

For example, this simple example executes the GetProcess command and returns the output collection. There are a lot of ways this could be improved, it's here as a simple example only, of course.

using System.Management.Automation;
using System.Collections.ObjectModel;

public class Test
{
    public static Collection<PSObject> RunCommand()
    {
        PowerShell psHost = PowerShell.Create();
        Collection<PSObject> output = psHost.AddCommand("Get-Process").AddArgument("powershell").Invoke();

        if (psHost.HadErrors)
        {
            foreach (ErrorRecord error in psHost.Streams.Error)
            {
                throw error.Exception;
            }
            return null;
        }
        else
        {
            return output;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM