Forms 事件通过ISE触发,但不在正常PS窗口中

Forms 事件通过ISE触发,但不在正常PS窗口中,forms,powershell,events,Forms,Powershell,Events,我通过谷歌尝试了很多“在ise中工作,但在控制台中不工作”的链接,尤其是在Stackoverflow上,但遗憾的是,到目前为止我还没有尝试过任何有效的链接 我将从整个代码开始: Param ( [ValidateRange(2,10)][int]$Time = 5, [ValidateLength(4,40)][String]$Title = "Attention $($Env:USERNAME.ToUpper())", [ValidateLength(4,40)][St

我通过谷歌尝试了很多“在ise中工作,但在控制台中不工作”的链接,尤其是在Stackoverflow上,但遗憾的是,到目前为止我还没有尝试过任何有效的链接

我将从整个代码开始:

Param (
    [ValidateRange(2,10)][int]$Time = 5,
    [ValidateLength(4,40)][String]$Title = "Attention $($Env:USERNAME.ToUpper())",
    [ValidateLength(4,40)][String]$Text = "This is a test!",
    [ValidateSet("None","Info","Warning","Error")] $Status = "Info",
    [ValidatePattern("[\\:\-\w\d\s]+.exe")][String]$TrayIcon = (Get-Process -id $pid).Path
)

# sec to ms
$TTL = $Time * 1000

if (![System.IO.File]::Exists($TrayIcon)){
    Write-Host "File does not exist!"
    exit
}

function ClearEvents {
    # Perform  cleanup actions on balloon tip
    $global:balloon.dispose()
    Remove-Variable  -Name balloon  -Scope Global

    Unregister-Event  -SourceIdentifier TrayClicked
    Remove-Job -Name TrayClicked

    Unregister-Event  -SourceIdentifier BallonClicked
    Remove-Job -Name BallonClicked

    Unregister-Event  -SourceIdentifier BalloonClosed
    Remove-Job -Name BalloonClosed

    #test if function is called
    [System.Windows.MessageBox]::Show('Hello')
}

Add-Type -AssemblyName System.Windows.Forms

$global:balloon = New-Object System.Windows.Forms.NotifyIcon

# Tray-Icon
$balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($TrayIcon)

# Balloon
# [System.Windows.Forms.ToolTipIcon] | Get-Member -Static -Type Property
$balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::$Status
$balloon.BalloonTipTitle = $Title
$balloon.BalloonTipText = $Text

$balloon.Visible = $true
$balloon.ShowBalloonTip($TTL)

[void](Register-ObjectEvent -InputObject $balloon -EventName MouseClick -SourceIdentifier TrayClicked -Action {
    ClearEvents
})
[void](Register-ObjectEvent -InputObject $balloon -EventName BalloonTipClicked -SourceIdentifier BallonClicked -Action {
    ClearEvents
})
[void](Register-ObjectEvent -InputObject $balloon -EventName BalloonTipClosed -SourceIdentifier BalloonClosed -Action {
    ClearEvents
})
现在,当其中一个事件被触发时(如单击气球),就会调用“ClearEvents”函数(出于测试目的,我添加了一个MsgBox)

但在控制台中,这些事件永远不会触发!为什么呢

使用Win7x64(PS 3.0)和Win10x64(PS 5.1)进行测试

我还通过
[System.Threading.Thread]:CurrentThread.GetApartmentState()
确认了这两个控制台都使用默认的“STA”(单线程单元)运行,显然有些“System.Windows.Forms”需要正确运行。 不幸的是,这不是问题所在


我的脚本基于此:

导致这些“在ISE中工作但不在控制台中”(或visa反之)问题的常见原因实际上不是ISE或控制台,而是(
$Global:
)变量,这些变量在一个实例中仍然可用,而在另一个实例中则不可用。换句话说:为了排除故障/确认您的问题描述,请重新启动(ISE和控制台)并确认它们的行为仍然不同(很可能它们都在重新启动后工作,但更有可能两者(包括ISE)都不再工作)。谢谢,我已经多次重新启动ISE或控制台;在不同的个人电脑上。