Powershell V5 Host (Windows Service) HANGS

Use this forum to ask questions after your subscription maintenance expires or before you buy. Need information on licensing or pricing? Questions about a trial version? This is the right place for you. No scripting questions, please.
Forum rules
DO NOT POST SUBSCRIPTION NUMBERS, LICENSE KEYS OR ANY OTHER LICENSING INFORMATION IN THIS FORUM.
Only the original author and our tech personnel can reply to a topic that is created in this forum. If you find a topic that relates to an issue you are having, please create a new topic and reference the other in your post.
This topic is 3 years and 1 month 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.
ericcmosby
Posts: 3
Last visit: Tue Feb 23, 2021 12:51 pm

Powershell V5 Host (Windows Service) HANGS

Post by ericcmosby »

Windows Service - HANGS when created with powershell studios

When using Sapien
Product: PowerShell Studio 2021 (64 Bit)
Build: v5.8.183
OS: Windows 10 Enterprise (64 Bit)
Build: v10.0.18363.0
to create a windows service with the following settings

DEPLOY - SETTINGS
SAPIEN Script Packager Version 1.0
PACKAGER - Script Engine -SAPIEN Powershell V5 Host (Windows Service)
Output Settings - Run Mode Current User
to create an EXE for
INSTALLER - 64 bit installer - Install for all users - Min PS ver 5
Service Settings - Error control ignore - service startup type demand -
service control - start none - stop both - remove uninstall

The service hangs if ANY error or warning occurs from line in script such as

$Socket = New-Object System.Net.Sockets.TCPClient($Address, $Port)
which is a line that creates an instance of .net framework or com object - event 4100

Script stops processing main script and powershell "start-jobs"

and subsequently event log reports - event 8197
Runspace state changed to Closing - event 8197
Runspace state changed to Closed - event 8197
and powershell "start-jobs" close and script takes no further actions

The script works fine if not packaged specifically to an "exe (windows service)" with SAPIEN

The script works fine if packaged to an "exe" NOT windows service with SAPIEN
This script works fine packaged to an exe with PS2EXE-GUI and run as service with NSSM
Please assist
User avatar
Alexander Riedel
Posts: 8473
Last visit: Tue Mar 19, 2024 1:15 am
Answers: 19
Been upvoted: 37 times

Re: Powershell V5 Host (Windows Service) HANGS

Post by Alexander Riedel »

There is no license associated with your account. Please clarify if this is a trial version.
Please submit a minimal script that exhibits the behavior. The script alone will suffice, we can package it as a service to investigate.
Alexander Riedel
SAPIEN Technologies, Inc.
ericcmosby
Posts: 3
Last visit: Tue Feb 23, 2021 12:51 pm

Re: Powershell V5 Host (Windows Service) HANGS

Post by ericcmosby »

This is a trial version yes.
Minimal code follows




Function Send-TCPMessage
{

Param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$EndPoint
,
[Parameter(Mandatory = $true, Position = 1)]
[int]$Port
,
[Parameter(Mandatory = $true, Position = 2)]
[string]$Message
)


Process
{

# Setup connection

$IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address, $Port); $error.clear()

# Setup stream wrtier
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream); $error.clear()

# Write message to stream
$Message | % {
$Writer.WriteLine($_)
$Writer.Flush()
}

# Close connection and stream
$Stream.Close()
$Socket.Close()
}


}
##########
#time for service to start
sleep -Seconds 15
#loop to check script active

While ($true)
{
# cause error because there is no listening port
Send-TCPMessage -Port 1234 -Endpoint 127.0.0.1 -message "cause error"
sleep -Seconds 5
#renew log file to see if script is still active
(get-date) | out-file c:\temp\LOG_LAST_ACTIVITY.log
$error | out-file c:\temp\LOG_LAST_ACTIVITY.log -Append
$Error.Clear()

}
User avatar
Alexander Riedel
Posts: 8473
Last visit: Tue Mar 19, 2024 1:15 am
Answers: 19
Been upvoted: 37 times

Re: Powershell V5 Host (Windows Service) HANGS

Post by Alexander Riedel »

The following is the template for a PowerShell Service in PowerShell Studio and PrimalScript. It contains a number of functions that cannot be renamed or omitted.
I suspect that if you follow the template you will not encounter the hanging problem. If you do, please let us know.
  1. <#        
  2.     .SYNOPSIS
  3.      A brief summary of the commands in the file.
  4.  
  5.     .DESCRIPTION
  6.     A detailed description of the commands in the file.
  7.  
  8.     .NOTES
  9.     ========================================================================
  10.          Windows PowerShell Source File
  11.          Created with SAPIEN Technologies PrimalScript 2021
  12.          
  13.          NAME:
  14.          
  15.          AUTHOR: %Username% , %Company%
  16.          DATE  : %Date%
  17.          
  18.          COMMENT:
  19.          
  20.     ==========================================================================
  21. #>
  22.  
  23. # Warning: Do not rename Start-MyService, Invoke-MyService and Stop-MyService functions
  24.  
  25. function Start-MyService
  26. {
  27.     # Place one time startup code here.
  28.     # Initialize global variables and open connections if needed
  29.     $global:bRunService = $true
  30.     $global:bServiceRunning = $false
  31.     $global:bServicePaused = $false;
  32. }
  33.  
  34. function Invoke-MyService
  35. {
  36.     $global:bServiceRunning = $true
  37.     while($global:bRunService) {
  38.         try
  39.         {
  40.             if($global:bServicePaused -eq $false) #Only act if service is not paused
  41.             {
  42.                 #Place code for your service here
  43.                 #e.g. $ProcessList = Get-Process solitaire -ErrorAction SilentlyContinue
  44.                
  45.                 # Use Write-Host or any other PowerShell output function to write to the System's application log
  46.             }          
  47.         }
  48.         catch
  49.         {
  50.             # Log exception in application log
  51.             Write-Host $_.Exception.Message
  52.         }      
  53.         # Adjust sleep timing to determine how often your service becomes active.
  54.         if($global:bServicePaused -eq $true)
  55.         {
  56.             Start-Sleep -Seconds 20 # if the service is paused we sleep longer between checks.
  57.         }
  58.         else
  59.         {
  60.             Start-Sleep –Seconds 10 # a lower number will make your service active more often and use more CPU cycles
  61.         }
  62.     }
  63.     $global:bServiceRunning = $false
  64. }
  65.  
  66. function Stop-MyService
  67. {
  68.     $global:bRunService = $false # Signal main loop to exit
  69.     $CountDown = 30 # Maximum wait for loop to exit
  70.     while($global:bServiceRunning -and $Countdown -gt 0)
  71.     {
  72.         Start-Sleep -Seconds 1 # wait for your main loop to exit
  73.         $Countdown = $Countdown - 1
  74.     }
  75.     # Place code to be executed on service stop here
  76.     # Close files and connections, terminate jobs and
  77.     # use remove-module to unload blocking modules
  78. }
  79.  
  80. function Pause-MyService
  81. {
  82.     # Service is being paused
  83.     # Save state
  84.     $global:bServicePaused = $true
  85.     # Note that the thread your PowerShell script is running on is not suspended on 'pause'.
  86.     # It is your responsibility in the service loop to pause processing until a 'continue' command is issued.
  87.     # It is recommended to sleep for longer periods between loop iterations when the service is paused
  88.     # in order to prevent excessive CPU usage by simply waiting and looping.
  89. }
  90.  
  91. function Continue-MyService
  92. {
  93.     # Service is being continued from a paused state
  94.     # Restore any saved states if needed
  95.     $global:bServicePaused = $false
  96. }
Alexander Riedel
SAPIEN Technologies, Inc.
This topic is 3 years and 1 month 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.