在用C#应用程序打开命令后,我无法向powershell控制台发送命令。我还尝试了其他方法,我在代码的底部注释了它,以向您展示我尝试过的内容。这是我在下面使用的代码:
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);
答案 0 :(得分:1)
@ChrisDent提出了一个很好的解决方案。
但是,代码中唯一的错误是,您必须在启动PowerShell之前设置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();
。试试这个:
TryAdd
答案 1 :(得分:-1)
为什么不直接与PowerShell交互?
例如,这个简单的示例执行GetProcess命令并返回输出集合。有很多方法可以改进,当然这只是一个简单的例子。
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;
}
}
}