Powershell脚本在ISE上运行良好,但在cli上存在问题

我编写了一个ps脚本,当我从ISE执行该脚本时就可以完成该工作,但是当我保存它并从CMD运行它时,我遇到了一个错误, 基本上,我已经用OU列表和GPO列表制作了gui,我想创建一个链接和取消链接按钮(例如,名为blabla的OU和名为GPOblabla的GPO,因此如果我同时选中它们并按链接,代码将链接和取消链接将取消链接) 问题是(据我所知)是在代码开头定义的button2(取消链接)功能,在该功能中,我使用了稍后在代码中使用参数的命令,我想ISE将它保存在内存中吗?什么是最好的事情在这里? 这是代码:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$button2_click = {
try {Remove-GPLink -Name $GPO -target $OU}
catch {
Write-Warning $Error[0]
} $form.close() }

$form = New-Object System.Windows.Forms.Form
$form.Text = 'GPO Connector V1.0'
$form.Size = New-Object System.Drawing.Size(600,200)
$form.StartPosition = 'CenterScreen'

$button1 = New-Object System.Windows.Forms.Button
$button1.Location = New-Object System.Drawing.Point(10,120)
$button1.Size = New-Object System.Drawing.Size(75,23)
$button1.Text = 'Link'
$button1.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $button1

$button2 = New-Object System.Windows.Forms.Button
$button2.Location = New-Object System.Drawing.Point(90,120)
$button2.Size = New-Object System.Drawing.Size(75,23)
$button2.Text = 'UnLink'
$Button2.Add_Click($Button2_Click)

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(80,20)
$label.Size = New-Object System.Drawing.Size(480,20)
$label.Text = 'SELECT GPO And Corresponding OU (ONLY WORKSTATION OU)'

$form.Controls.Add($label)
$form.Controls.Add($button1)
$form.Controls.Add($button2)

$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 80

$listBox2 = New-Object System.Windows.Forms.ListBox
$listBox2.Location = New-Object System.Drawing.Point(300,40)
$listBox2.Size = New-Object System.Drawing.Size(260,20)
$listBox2.Height = 80

#gpolist.txt holding the gpo's and oulist.txt would hold the ou's
Get-Content .\gpolist.txt | ?{$_ -notmatch "^#"}  | Where-Object { $_.Trim() -ne '' } | ForEach-Object {
[void] $listBox.Items.Add("$_")}

Get-Content .\oulist.txt | ?{$_ -notmatch "^#"} | Where-Object { $_.Trim() -ne '' } | ForEach-Object {
[void] $listBox2.Items.Add("$_")}

$form.Controls.Add($listBox)
$form.Controls.Add($listBox2)
$form.Topmost = $true
$result = $form.ShowDialog()


if ($result -eq [System.Windows.Forms.DialogResult]::Cancel)
{   break   }


if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$GPO = $listBox.SelectedItem
$OU = $listBox2.SelectedItem    }

New-GPLink $GPO -target $OU | out-null }