Tray Application Run script on exit

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 5 months and 2 weeks old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
andybabin
Posts: 1
Last visit: Tue Jun 18, 2024 3:40 pm

Tray Application Run script on exit

Post by andybabin »

To help you better we need some information from you.

*** Please fill in the fields below. If you leave fields empty or specify 'latest' rather than the actual version your answer will be delayed as we will be forced to ask you for this information. ***

Product, version and build: Powershell Studio 5.8.241
Operating system: Windows 10 22H2
PowerShell version(s):

*** Please add details and screenshots as needed below. ***

DO NOT POST LICENSES, KEYS OR ANY OTHER LICENSING INFORMATION IN THIS FORUM

I have a tray app that I'm writing, is it possible to execute code when the app is exited or receives the quit command from windows?

Right now the app is a basic while loop.
  1. #Define a Param block to use custom parameters in the project
  2. #Param ($CustomParameter)
  3.  
  4. #Grab make and model info
  5. $model = (Get-WmiObject -Class:Win32_ComputerSystem).Model;
  6.  
  7. #Check if this is 4u Threadripper, if so open com3
  8. if ($model -eq "Early 2024 Fusebox 4u") { $port = new-Object System.IO.Ports.SerialPort COM3, 115200, None, 8, one; Write-Host("2024 Fusebox 4u") }
  9. elseif ($model -eq "Mid 2024 Fusebox 1u") { $port = new-Object System.IO.Ports.SerialPort COM3, 115200, None, 8, one; Write-Host("2024 Fusebox 1u") }
  10. elseif ($model -eq "System Product Name") { $port = new-Object System.IO.Ports.SerialPort COM3, 115200, None, 8, one; Write-Host("BabinTest") }
  11. else { Write-Host("No matching ports found"); Write-Host($model) }
  12.  
  13.  
  14. function Main
  15. {
  16. <#
  17.     .SYNOPSIS
  18.         The Main function starts the project application.
  19.    
  20.     .PARAMETER Commandline
  21.         $Commandline contains the complete argument string passed to the script packager executable.
  22.    
  23.     .NOTES
  24.         Use this function to initialize your script and to call GUI forms.
  25.        
  26.     .NOTES
  27.         To get the console output in the Packager (Forms Engine) use:
  28.         $ConsoleOutput (Type: System.Collections.ArrayList)
  29. #>
  30.     Param ([String]$Commandline)
  31.    
  32.     #--------------------------------------------------------------------------
  33.     #TODO: Add initialization script here (Load modules and check requirements)
  34.     Add-Type -AssemblyName "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
  35.     #[void][System.Windows.Forms.MessageBox]::Show('TODO: Add script to the Main function of Startup.pss', 'TODO')
  36.  
  37.     # Grab Serial ports
  38.     #$serial_ports= Get-CimInstance -Class Win32_SerialPort | Select-Object Name, DeviceID ;
  39.  
  40.     # Looks for external config file
  41.     Write-Debug "Reading configuration."
  42.     try
  43.     {
  44.         . $PSScriptRoot/config.ps1
  45.     }
  46.     catch
  47.     {
  48.         Write-Debug "Error reading setup file."
  49.         EXIT
  50.     }
  51.    
  52.  
  53.     #loop to run watchdog script
  54.  
  55.    
  56.     try
  57.     {
  58.         while ($port)
  59.         {
  60.             $port.open() # Open Serial Port
  61.            
  62.             if (Get-Process -ErrorAction SilentlyContinue -Name "VLC") { $port.WriteLine($preset_101) }
  63.             elseif (Get-Process -ErrorAction SilentlyContinue -Name "cmd") { $port.WriteLine($preset_107) } #Matrix
  64.             #elseif (Get-Process -ErrorAction SilentlyContinue -Name "d3manager") {$port.WriteLine($preset_3)}
  65.            
  66.             else { $port.WriteLine($preset_100) } #Windows Idle
  67.             write-debug "in loop"
  68.             $port.Close() # Close Serial Port
  69.             Start-Sleep -Seconds 1 # Wait time
  70.         }
  71.        
  72.     }
  73.    
  74.     catch
  75.     {
  76.         # Catch any error
  77.         Write-Debug "An error occurred"
  78.     }
  79.     finally
  80.     {
  81.         # [Optional] Run this part always
  82.         $port.Close() # Close Serial Port
  83.         Write-Host("quitting")
  84.     }
  85.    
  86.     #--------------------------------------------------------------------------
  87.    
  88.  
  89.     $script:ExitCode = 0 #Set the exit code for the Packager
  90. }

Edit: I tried making it a windows service project as well as I noticed that has a "Stop-MyService" function. However this doesn't appear to be called on windows shutdown, only if I stop the service manually.

The below code is what I'm trying with a service
  1.  
  2. # Warning: Do not rename Start-MyService, Invoke-MyService and Stop-MyService functions
  3.  
  4.  
  5. function Start-MyService
  6. {
  7.     # Place one time startup code here.
  8.     # Initialize global variables and open connections if needed
  9.     Write-Host "Serive Start Function"
  10.     $global:bRunService = $true
  11.     $global:bServiceRunning = $false
  12.     $global:bServicePaused = $false
  13. }
  14.  
  15. function Invoke-MyService
  16. {
  17.     Write-Host "Service Invoke Function"
  18.     $global:bServiceRunning = $true
  19.     while($global:bRunService) {
  20.         try
  21.         {
  22.             if($global:bServicePaused -eq $false) #Only act if service is not paused
  23.             {
  24.                 #Place code for your service here
  25.                 #e.g. $ProcessList = Get-Process solitaire -ErrorAction SilentlyContinue
  26.                
  27.                 # Use Write-Host or any other PowerShell output function to write to the System's application log
  28.             }
  29.         }
  30.         catch
  31.         {
  32.             # Log exception in application log
  33.             Write-Host $_.Exception.Message
  34.         }
  35.         # Adjust sleep timing to determine how often your service becomes active.
  36.         if($global:bServicePaused -eq $true)
  37.         {
  38.             Start-Sleep -Seconds 20 # if the service is paused we sleep longer between checks.
  39.         }
  40.         else
  41.         {
  42.             Start-Sleep –Seconds 10 # a lower number will make your service active more often and use more CPU cycles
  43.         }
  44.     }
  45.     $global:bServiceRunning = $false
  46. }
  47.  
  48. function Stop-MyService
  49. {
  50.     Write-Host "Stop Service Function"
  51.     $global:bRunService = $false # Signal main loop to exit
  52.     $CountDown = 30 # Maximum wait for loop to exit
  53.     while($global:bServiceRunning -and $Countdown -gt 0)
  54.     {
  55.         Start-Sleep -Seconds 1 # wait for your main loop to exit
  56.         $Countdown = $Countdown - 1
  57.     }
  58.     # Place code to be executed on service stop here
  59.     # Close files and connections, terminate jobs and
  60.     # use remove-module to unload blocking modules
  61. }
  62.  
  63. function Pause-MyService
  64. {
  65.     Write-Host "Pause Service Function"
  66.     # Service is being paused
  67.     # Save state
  68.     $global:bServicePaused = $true
  69.     # Note that the thread your PowerShell script is running on is not suspended on 'pause'.
  70.     # It is your responsibility in the service loop to pause processing until a 'continue' command is issued.
  71.     # It is recommended to sleep for longer periods between loop iterations when the service is paused.
  72.     # in order to prevent excessive CPU usage by simply waiting and looping.
  73. }
  74.  
  75. function Continue-MyService
  76. {
  77.     Write-Host "Continue Service Function"
  78.     # Service is being continued from a paused state
  79.     # Restore any saved states if needed
  80.     $global:bServicePaused = $false
  81. }
  82.  
  83.  
User avatar
brittneyr
Site Admin
Posts: 1805
Last visit: Fri Nov 08, 2024 11:17 am
Answers: 44
Been upvoted: 34 times

Re: Tray Application Run script on exit

Post by brittneyr »

[Topic moved by moderator to PowerShell Forum]
Brittney
SAPIEN Technologies, Inc.
User avatar
brittneyr
Site Admin
Posts: 1805
Last visit: Fri Nov 08, 2024 11:17 am
Answers: 44
Been upvoted: 34 times

Re: Tray Application Run script on exit

Post by brittneyr »

You cannot do that from one application. An application cannot run code after it has exited.
Brittney
SAPIEN Technologies, Inc.
This topic is 5 months and 2 weeks old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked