ให้เขียนโค้ดต่างใน notepad แล้วsave เป็น winformtest.ps1
จากนั้นทดสอบรันโค้ดนี้ ใน powershell
โดยเรียกใช้ดังนี้
.\winformtest.ps1
(ให้เปลี่ยนไปยัง path ที่เก็บไฟล์ winformtest.ps1)
หรืออาจจะเรียกใช้โดยคำสั่ง
Invoke-Expression .\windowtest.ps1 ก้ได้
ผลลัพธ์จะได้
ดังรูป

และเมื่อคลิกที่ button ก็จะแสดงข้อความออกมาดังรูป

ตัวอย่างโค้ด
#file: windowtest.ps1
# เรียกใช้งาน library
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
#สร้าง หน้า Window
$winform = New-Object "System.Windows.Forms.Form";
$winform.Size = New-Object System.Drawing.Size @(500,500);
$winform.Text ="Test Window";
#สร้าง control
$txtbox = New-Object "System.Windows.Forms.TextBox";
$btn = New-Object "System.Windows.Forms.Button";
#กำหนด Properties ต่างๆให้กับ Button
$btn.Text ="Submit";
$btn.Width = 50;
$btn.Height = 50;
#กำหนด Event add_Click เมื่อมีการคลิกที่ button ก็ให้แสดง Hello ออกมา
$btn.add_Click({
Write-Host "Hello";
});
#เพิ่ม Controls ต่างเข้าไปใน winform
$winform.Controls.Add($txtbox);
$winform.Controls.Add($btn);
#แสดง winform
$winform.ShowDialog()
[With great power comes great responsibility]