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
Powershell V5 Host (Windows Service) HANGS
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.
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.
-
- Posts: 3
- Last visit: Tue Feb 23, 2021 12:51 pm
- Alexander Riedel
- Posts: 8488
- Last visit: Tue Apr 16, 2024 8:42 am
- Been upvoted: 37 times
Re: Powershell V5 Host (Windows Service) HANGS
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.
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.
SAPIEN Technologies, Inc.
-
- Posts: 3
- Last visit: Tue Feb 23, 2021 12:51 pm
Re: Powershell V5 Host (Windows Service) HANGS
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()
}
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()
}
- Alexander Riedel
- Posts: 8488
- Last visit: Tue Apr 16, 2024 8:42 am
- Been upvoted: 37 times
Re: Powershell V5 Host (Windows Service) HANGS
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.
I suspect that if you follow the template you will not encounter the hanging problem. If you do, please let us know.
- <#
- .SYNOPSIS
- A brief summary of the commands in the file.
- .DESCRIPTION
- A detailed description of the commands in the file.
- .NOTES
- ========================================================================
- Windows PowerShell Source File
- Created with SAPIEN Technologies PrimalScript 2021
- NAME:
- AUTHOR: %Username% , %Company%
- DATE : %Date%
- COMMENT:
- ==========================================================================
- #>
- # Warning: Do not rename Start-MyService, Invoke-MyService and Stop-MyService functions
- function Start-MyService
- {
- # Place one time startup code here.
- # Initialize global variables and open connections if needed
- $global:bRunService = $true
- $global:bServiceRunning = $false
- $global:bServicePaused = $false;
- }
- function Invoke-MyService
- {
- $global:bServiceRunning = $true
- while($global:bRunService) {
- try
- {
- if($global:bServicePaused -eq $false) #Only act if service is not paused
- {
- #Place code for your service here
- #e.g. $ProcessList = Get-Process solitaire -ErrorAction SilentlyContinue
- # Use Write-Host or any other PowerShell output function to write to the System's application log
- }
- }
- catch
- {
- # Log exception in application log
- Write-Host $_.Exception.Message
- }
- # Adjust sleep timing to determine how often your service becomes active.
- if($global:bServicePaused -eq $true)
- {
- Start-Sleep -Seconds 20 # if the service is paused we sleep longer between checks.
- }
- else
- {
- Start-Sleep –Seconds 10 # a lower number will make your service active more often and use more CPU cycles
- }
- }
- $global:bServiceRunning = $false
- }
- function Stop-MyService
- {
- $global:bRunService = $false # Signal main loop to exit
- $CountDown = 30 # Maximum wait for loop to exit
- while($global:bServiceRunning -and $Countdown -gt 0)
- {
- Start-Sleep -Seconds 1 # wait for your main loop to exit
- $Countdown = $Countdown - 1
- }
- # Place code to be executed on service stop here
- # Close files and connections, terminate jobs and
- # use remove-module to unload blocking modules
- }
- function Pause-MyService
- {
- # Service is being paused
- # Save state
- $global:bServicePaused = $true
- # Note that the thread your PowerShell script is running on is not suspended on 'pause'.
- # It is your responsibility in the service loop to pause processing until a 'continue' command is issued.
- # It is recommended to sleep for longer periods between loop iterations when the service is paused
- # in order to prevent excessive CPU usage by simply waiting and looping.
- }
- function Continue-MyService
- {
- # Service is being continued from a paused state
- # Restore any saved states if needed
- $global:bServicePaused = $false
- }
Alexander Riedel
SAPIEN Technologies, Inc.
SAPIEN Technologies, Inc.