【问题标题】:How do I run a simple Powershell command from my C# project in Visual Studio 2015?如何在 Visual Studio 2015 中从我的 C# 项目运行简单的 Powershell 命令?
【发布时间】:2018-12-13 19:27:21
【问题描述】:

我有一个简单的单行 Powershell 命令,可以取消阻止特定文件夹中的所有 dll。我想在 VS 2015 中通过我的 C# main() 方法运行此命令。

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

我该怎么做?我可能必须安装的任何扩展程序?

【问题讨论】:

  • 你不能使用Process.Start吗?
  • 不知道,因为我是 c# 的初学者。能详细点吗?
  • 检查我的答案:)

标签: c# visual-studio powershell


【解决方案1】:

试试下面的,Process.Start 应该做你需要的。

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

【讨论】:

    【解决方案2】:

    首先,我喜欢这个问题。我是 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);
            }
        }
    }
    

    这应该为您完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2018-06-05
      • 2015-11-05
      • 1970-01-01
      • 2019-07-31
      • 2016-03-21
      • 2019-08-14
      • 2015-04-26
      相关资源
      最近更新 更多