Author Posts

September 12, 2014 at 6:22 am

Somebody know why this script works fine in Powershell_ISE but when running in the console doesn't seem to catch the click events?

[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)#Remove any registered events related to notifications
Remove-Event BalloonClicked_event -ea SilentlyContinue
Unregister-Event -SourceIdentifier BalloonClicked_event -ea silentlycontinue
Remove-Event BalloonClosed_event -ea SilentlyContinue
Unregister-Event -SourceIdentifier BalloonClosed_event -ea silentlycontinue#Create the notification object
$notification = New-Object System.Windows.Forms.NotifyIcon

#Define the icon for the system tray
$notification.Icon = [System.Drawing.SystemIcons]::Information

#Display title of balloon window
$notification.BalloonTipTitle = “This is a Balloon Title”

#Type of balloon icon
$notification.BalloonTipIcon = “Info”

#Notification message
$title = “This is the message in the balloon tip.”
$notification.BalloonTipText = $title

#Make balloon tip visible when called
$notification.Visible = $True

## Register a click event with action to take based on event
#Balloon message clicked
register-objectevent $notification BalloonTipClicked BalloonClicked_event `
-Action {.\Test.ps1} | Out-Null

#Balloon message closed
register-objectevent $notification BalloonTipClosed BalloonClosed_event `
-Action {[System.Windows.Forms.MessageBox]::Show(“Balloon message closed”,”Information”);$notification.Visible = $False} | Out-Null

#Call the balloon notification

September 12, 2014 at 7:13 am

The ISE is a Windows Forms application, so it is already set up to handle windows messages from the notify icon. PowerShell.exe, on the other hand, is a console application. While you can use some Windows Forms classes successfully from a console app, some things (such as the notify icon events, as you've discovered) don't work quite the same way. If you search the web for [b]NotifyIcon Console Application[/b], you'll get all sorts of results from C# programmers running into the same issue. The catch is that many of the solutions you'll find for this problem involve multiple threads, which are tricky to do properly in PowerShell.