「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.18
XML
カテゴリ: C#.NET


C# WPF アプリケーションから PowerShell を呼び出す方法はいくつかありますが、一般的な方法は `System.Diagnostics.Process` クラスを使用することです。以下は、PowerShell を呼び出してスクリプトを実行するサンプルコードです。


```csharp

using System;

using System.Diagnostics;

using System.IO;

using System.Windows;


namespace CallPowerShellExample

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }


        private void CallPowerShellScript_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                // PowerShell スクリプトのパス

                string scriptPath = @"C:\path\to\your\script.ps1";


                // PowerShell を実行するためのプロセス情報を作成

                ProcessStartInfo startInfo = new ProcessStartInfo

                {

                    FileName = "powershell.exe",

                    Arguments = $"-File \"{scriptPath}\"", // スクリプトのパスを引数として渡す

                    RedirectStandardOutput = true,

                    UseShellExecute = false,

                    CreateNoWindow = true // PowerShell ウィンドウを表示しない

                };


                // PowerShell プロセスを開始して実行

                using (Process process = Process.Start(startInfo))

                {

                    // PowerShell スクリプトの実行が終了するまで待機

                    process.WaitForExit();


                    // PowerShell スクリプトの出力を読み取り

                    string output = process.StandardOutput.ReadToEnd();


                    // 出力を表示

                    MessageBox.Show(output, "PowerShell Output", MessageBoxButton.OK, MessageBoxImage.Information);

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show($"Error occurred: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            }

        }

    }

}

```


このコードでは、`ProcessStartInfo` クラスを使用して PowerShell スクリプトのパスを指定し、`powershell.exe` を呼び出してスクリプトを実行しています。`-File` パラメータを使用してスクリプトのパスを渡し、`RedirectStandardOutput` プロパティを使用して PowerShell スクリプトの出力をリダイレクトします。`CreateNoWindow` プロパティを使用して PowerShell ウィンドウを表示しないようにします。


また、`process.WaitForExit()` を使用して PowerShell スクリプトの実行が終了するまで待機し、`process.StandardOutput.ReadToEnd()` を使用して PowerShell スクリプトの出力を読み取ります。


これにより、C# WPF アプリケーションから PowerShell スクリプトを呼び出して実行し、その出力を取得して表示することができます。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.18 08:23:34


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
X
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: