C# を PowerShell で実行 : Form 内のテキストフィールドに入力した結果をファイルに書き込む

PowerShell のコマンドウインドウで実行すると、2回目以降がエラーになるので、powershell に引数を渡して(バッチファイル)実行させています。

バッチ処理で、どうしても複雑な入力パラメータが必要な時に使えると思います。

関連する記事

C# を PowerShell で実行 : メッセージボックスの応答結果をファイルに書き込む ( バッチファイルで利用可能 )


form1.ps1
$code = @"
using System;
using System.IO;
using System.Windows.Forms;
public class MyClass {

	// ▼ これは無くても動作する
	[STAThread]
	public static void Main()
	{
		// テンプレート部分( 最初から記述されている )
		Application.EnableVisualStyles();
		Application.SetCompatibleTextRenderingDefault(false);
		// Form1 の作成
		Application.Run(new Form1());
	}

	// Form1 クラス
	private class Form1 : Form
	{
		// コンストラクタ
		public Form1()
		{
			InitializeComponent();
		}

		// 画面作成( デザイナが作成したもの )
		private void InitializeComponent()
		{
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			// 
			// textBox1
			// 
			this.textBox1.Location = new System.Drawing.Point(47, 49);
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(191, 19);
			this.textBox1.TabIndex = 0;
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(274, 47);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(75, 23);
			this.button1.TabIndex = 1;
			this.button1.Text = "実行";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.button1_Click);

			//this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(400, 150);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.textBox1);
			this.Text = "フォームのタイトル";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
		}

		// ボタンをクリックした時のイベント
		private void button1_Click(object sender, EventArgs e)
		{
			Console.WriteLine("button1_Click");

			// テンポラリフォルダのパスを取得
			string path = Environment.GetEnvironmentVariable("temp");

			// 書き込むファイルのフルパスを編集する
			string writePath = string.Format( @"{0}\_input_result", path );

			using (StreamWriter sw = new StreamWriter(writePath, false))
			{
				// 書き込み
				sw.Write( textBox1.Text );

				// ファイルを閉じます
				sw.Close();

			}

			// アプリケーション終了
			Application.Exit();
		}

		// コントロール用変数
		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.Button button1;
	}
}
"@

Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("System.Windows.Forms","System.Drawing")

[MyClass]::Main()



form1.bat
@powershell -NoProfile -ExecutionPolicy Unrestricted "./form1.ps1"