[英]How do I run a simple Powershell command from my C# project in Visual Studio 2015?
I have a simple one line Powershell command which unblocks all dlls in a specific folder. 我有一个简单的单行Powershell命令,它可以解除阻止特定文件夹中的所有dll。 I want to run this command from my C#
main()
method in VS 2015. 我想从VS 2015中的C#
main()
方法运行此命令。
I have tried using Runspace
but VS is not recognizing it. 我尝试使用运行
Runspace
但VS无法识别它。
How can I do this ? 我怎样才能做到这一点 ? Any extensions that I might have to install ?
我可能必须安装任何扩展程序吗?
试试下面的过程, Process.Start
应该根据需要执行。
System.Diagnostics.Process.Start("Path/To/Powershell/Script.ps1");
First off, I love the question. 首先,我喜欢这个问题。 I'm a serious PowerShell fan and love to figure out something new about PowerShell almost every day.
我是PowerShell的忠实粉丝,几乎每天都想了解有关PowerShell的新知识。
Now, for the answer. 现在,为答案。
Here's what I'm going to do. 这就是我要做的。 First, I'm going to open up PowerShell, without making the window show up.
首先,我将打开PowerShell,而不会显示该窗口。 Then, I'm going to run the Get-Process command, since it provides some good info.
然后,我将运行Get-Process命令,因为它提供了一些不错的信息。 Finally, I'm going to print the results to a screen, then wait for the user to press any key to verify that they saw the response.
最后,我将结果打印到屏幕上,然后等待用户按任意键来验证他们是否看到了响应。 (If you want it in a string, look into StringBuilder.) This will basically do what you asked;
(如果要在字符串中使用它,请查看StringBuilder。)这基本上可以满足您的要求; run a single, simple command, and get the output.
运行一个简单的命令,并获取输出。
Here's the code. 这是代码。
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);
}
}
}
This should do the job for you. 这应该为您完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.