简体   繁体   English

从C#发出Powershell命令以进行控制台

[英]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. 使用C#应用程序打开Powershell控制台后,无法将命令发送到该控制台。 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. @ChrisDent建议一个很好的解决方案。

However, the only error with you code is, that you have to set the StartInfo before starting the powershell. 但是,代码唯一的错误是,必须在启动StartInfo之前设置StartInfo 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? 为什么不直接与PowerShell交互?

For example, this simple example executes the GetProcess command and returns the output collection. 例如,这个简单的示例执行GetProcess命令并返回输出集合。 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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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