LoginSignup
8
13

More than 5 years have passed since last update.

C#からPowerShellコマンドの実行

Last updated at Posted at 2018-04-17

Windowsサーバのパフォーマンスチェックアプリを作成する際に、PowerShellのGet-Processコマンドをダンプさせたかったので、
その調査内容のメモです。コンソールアプリケーションにコピペ->開始で動作します。コード詳細はコメントを参照願います。

using System.Diagnostics;
namespace ConsoleApp2
{
    class Program
    {
        // パワーシェルコマンド固定値定義
        const string ps_command = @"Get-Process | Get-Process | Sort-Object PM -Descending | Out-File -FilePath ";
        static void Main(string[] args)
        {
            // パワーシェルのGet-Processをダンプしたかったのでここで出力ファイル定義(可変)を実行させる。
            string option = ps_command + @"C:\temp\dump.txt";
            OpenWithArguments(option);  // メソッド呼び出し
        }
        //PowerShellの実行メソッド(引数:PowerShellコマンド)
        static void OpenWithArguments(string options)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "PowerShell.exe";
            //PowerShellのWindowを立ち上げずに実行。
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
            // 引数optionsをShellのコマンドとして渡す。
            cmd.StartInfo.Arguments = options;
            cmd.Start();
        }
    }
}
8
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
13