繁体   English   中英

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

[英]How do I run a simple Powershell command from my C# project in Visual Studio 2015?

我有一个简单的单行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);
        }
    }
}

这应该为您完成工作。

暂无
暂无

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

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