'Powershell Winforms doesn't execute button_click action locally

I'm making winforms with powershell for the first time.

I was working hard on it. but I ran into a problem. I tried to solve it by myself, but I don't know..

When I run the below code in powershell ise, $button_click works. In other words, it worked fine in ise.

However, after saving to the desktop, $button_click does not work when running through cmd.

# start.bat
C:\Users\User\Desktop> powershell -ExecutionPolicy Unrestricted %CD%\code.ps1

I wrote the following code:

# code.ps1
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
   
# form specs
$Form = New-object System.Windows.Forms.Form
$Form.Text = "Check Network Status"
$Form.Size = New-object System.Drawing.Size(700,700)
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = "None"
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.BackColor = "Lavender"
 
# form icon
$Icon = New-object system.drawing.icon ("icon.ico")
$Form.Icon = $Icon
 
# form image
$Image = [system.drawing.image]::FromFile("img.jpg")
$PictureBox = New-Object System.Windows.Forms.PictureBox
$PictureBox.Image = $Image
$PictureBox.Size = New-object System.Drawing.Size(700,550)
$PictureBox.SizeMode = "StretchImage"
$Form.Controls.Add($PictureBox)
 
# ok button
$ButtonSizeWidth = 200
$ButtonSizeHeight = 50
$Button = New-object System.Windows.Forms.Button
$Font = New-Object System.Drawing.Font("Arial",20)
$Button.Location = New-object System.Drawing.Size((350 - $ButtonSizeWidth / 2),(650 - $ButtonSizeHeight))
$Button.Size = New-object System.Drawing.Size($ButtonSizeWidth,$ButtonSizeHeight)
$Button.Text = "Okay"
$Button.BackColor = "PowderBlue"
$Button.FlatAppearance.BorderSize = 0
$Button.FlatStyle = "Flat"
$Button.Font = $Font
$Button.Add_Click($button_click)
$Form.Controls.Add($Button)
 
# action here
$button_click =
{
    # netsh int set int admin=disable
    $Form.Close()
}  
   
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter"){& $button_click}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$Form.Close()}})
   
# modal
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

Obviously it works fine in powershell ise, but I want to know why it doesn't work when I save and run it.

Is there something I'm missing out on?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source