从c#发出Powershell命令到控制台
本文关键字:控制台 命令 Powershell 发出 | 更新日期: 2023-09-27 18:01:17
我用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);
@ChrisDent提出了一个很好的解决方案。
然而,你的代码唯一的错误是,你必须在启动powershell之前设置StartInfo
。试试这个:
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();
为什么不直接与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;
}
}
}