3

I want to see a little notification icon to indicate that the script I wrote is still active (both the script and displying the icon works). But I need a button within the context menu of the icon to stop the script immediately. And that's the part where my problem is:

$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon 
$objContextMenu = New-Object System.Windows.Forms.ContextMenu
$ExitMenuItem = New-Object System.Windows.Forms.MenuItem

$ExitMenuItem.add_Click({
   echo stoped
   $continue = $False
   $objNotifyIcon.visible = $False
})

$objContextMenu.MenuItems.Add($ExitMenuItem) | Out-Null
$objNotifyIcon.ContextMenu = $objContextMenu
$objNotifyIcon.Visible = $True

The script itself is longer, this is just the relevant part. If I run it from PowerShell ISE it works just fine. When I run it from a .bat file with

powershell .\myscript.ps1

the context menu is not working anymore.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Hans Dampf
  • 67
  • 7
  • 2
    Please be more specific than "the context menu is not working anymore." - does it no longer show when you right-click the NotifyIcon? Does it display but has no effect when you click it? Do you get unexpected errors? – Mathias R. Jessen Mar 07 '16 at 12:11
  • 1
    What are your PowerShell and Windows version? Check the [threading mode](https://blogs.msdn.microsoft.com/powershell/2009/04/17/differences-between-the-ise-and-powershell-console/) is the same in console and ISE (`$host.RunSpace.ApartmentModel`). – Ansgar Wiechers Mar 07 '16 at 12:32
  • great, thank you! starting powershell with -sta did it. – Hans Dampf Mar 07 '16 at 13:00

1 Answers1

1

This is just a wild guess, but try running the script in Single Thread Apartment mode:

powershell -STA -File .\myscript.ps1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328