如何在Visual Studio 2015中从我的C#项目运行一个简单的Powershell命令?



我有一个简单的单行Powershell命令,可以解锁特定文件夹中的所有dll。我想从VS 2015中的C#main()方法运行此命令。

我尝试使用Runspace但VS无法识别它。

我该怎么做?我可能需要安装的任何扩展?

尝试以下操作,Process.Start应该根据需要进行操作。

System.Diagnostics.Process.Start("Path/To/Powershell/Script.ps1");

首先,我喜欢这个问题。我是一个忠实的PowerShell粉丝,几乎每天都喜欢了解PowerShell的新知识。

现在,为了答案。

这就是我要做的。首先,我将打开PowerShell,而不显示窗口。然后,我将运行 Get-Process 命令,因为它提供了一些很好的信息。最后,我将结果打印到屏幕上,然后等待用户按任意键以验证他们是否看到了响应。(如果你想把它放在一个字符串中,请查看StringBuilder。这基本上会按照你的要求做;运行单个简单的命令,并获取输出。

这是代码。

using System;
using System.Diagnostics;
namespace powershellrun {
public class program {
public static void Main(string[] args) {
//Open up PowerShell with no window
Process ps = new Process();
ProcessStartInfo psinfo = new ProcessStartInfo();
psinfo.FileName = "powershell.exe";
psinfo.WindowStyle = ProcessWindowStyle.Hidden;
psinfo.UseShellExecute = false;
psinfo.RedirectStandardInput = true;
psinfo.RedirectStandardOutput = true;
ps.StartInfo = psinfo;
ps.Start();
//Done with that.
//Run the command.
ps.StandardInput.WriteLine("Get-Process");
ps.StandardInput.Flush();
ps.StandardInput.Close();
ps.WaitForExit();
//Done running it.
//Write it to the console.
Console.WriteLine(ps.StandardOutput.ReadToEnd());
//Done with everything.
//Wait for the user to press any key.
Console.ReadKey(true);
}
}
}

这应该为您完成工作。

最新更新