Skip to content

Servy PowerShell Module

Akram El Assas edited this page Aug 21, 2026 · 113 revisions

Table of Contents

  1. Introduction
  2. Installation
  3. Usage Examples
  4. Cmdlets Reference
  5. Troubleshooting
  6. See Also
  7. References

Important

Console UI Compatibility If your app tries to visually update the command prompt (like clearing the screen or moving the cursor), it will crash when running as a background service since services don't have visible windows. To fix this without changing your code, enable the -EnableConsoleUI option in the service configuration while installing your service.

Introduction

The Servy PowerShell Module provides a lightweight, scriptable interface for managing background services. It is designed to be highly portable, allowing sysadmins to automate deployments across diverse Windows environments.

Compatibility & Runtime Requirements

The PowerShell module (Servy.psm1) is authored to be compatible with PowerShell 2.0 and later. However, its ability to run on older operating systems depends on which version of the Servy CLI is present:

  • For Windows 10 / 11 / Server 2016+: Use the Modern CLI (.NET 10.0+). This version offers the best performance and utilizes the latest Windows security features.
  • For Windows 7 SP1 / 8 / Server 2008 R2: Use the Legacy CLI (.NET Framework 4.8). When paired with this build, the PowerShell module is fully functional on older distributions.

Note

The Task Scheduler hooks shipped under taskschd/ (ServyFailureEmail.ps1, ServyFailureNotification.ps1, Get-ServyLastErrors.ps1, Servy-Watermark.psm1) have stricter requirements:

  • Get-WinEvent-based scripts need PowerShell 5.1+ (Windows 7 SP1 / Server 2008 R2 SP1+).
  • Toast notifications need PowerShell 5.1+ (Windows 10 1607+). Only Servy.psm1 itself is fully PS 2.0 compatible.

Installation

Import the module in your PowerShell session:

Import-Module "C:\Program Files\Servy\Servy.psm1" -Force

Display the version:

Get-ServyVersion

Display help:

# View general module help and available commands
Get-ServyHelp

# Get help for other supported commands
Get-ServyHelp -Command "install"
Get-ServyHelp -Command "start"
Get-ServyHelp -Command "stop"

Usage Examples

Pro Tip: In PowerShell, switch parameters (like -Quiet, -Install, or -EnableHealth) are toggle flags. When calling a command inline, do not pass values like $true or $false; including the flag enables it, and omitting it leaves it disabled. When using parameter splatting, it is correct and idiomatic to set switch parameters to $true in the splat hashtable.

Why use parameter splatting?

Parameter splatting makes PowerShell commands easier to read, maintain, and extend.

Instead of long command lines with many parameters, options are grouped into a single hashtable that clearly shows intent and defaults. This is especially useful for Servy commands, which support many optional parameters and advanced scenarios such as hooks, logging, and recovery configuration.

Splatting also:

  • Avoids line continuation backticks
  • Makes it easier to add or remove parameters
  • Keeps examples readable as the API evolves

Install a New Service

# CORRECT: Switch flags are included by presence or set to $true in the splat hashtable
$installParams = @{
    Name              = "WexflowServer"
    Description       = "Wexflow Workflow Engine"
    Path              = "C:\Program Files\dotnet\dotnet.exe"
    StartupDir        = "C:\Program Files\Wexflow Server\Wexflow.Server"
    Params            = "Wexflow.Server.dll"
    StartupType       = "Automatic"
    EnableHealth      = $true
    RecoveryAction    = "RestartService"
    HeartbeatInterval = 30
    MaxFailedChecks   = 3
}

Install-ServyService @installParams

# INCORRECT: Do not do this with inline switches
# Install-ServyService -Quiet $true -EnableHealth $true

# CORRECT: Use inline switches without values, or use splatting
# Inline: Install-ServyService -Quiet -EnableHealth
# Splatting:
# $params = @{ Quiet = $true; EnableHealth = $true }
# Install-ServyService @params

Export Service Configuration

$exportXmlParams = @{
    Name           = "WexflowServer"
    ConfigFileType = "xml"
    Path           = "C:\WexflowServer.xml"
}

Export-ServyServiceConfig @exportXmlParams

$exportJsonParams = @{
    Name           = "WexflowServer"
    ConfigFileType = "json"
    Path           = "C:\WexflowServer.json"
}

Export-ServyServiceConfig @exportJsonParams

Import Service Configuration

# CORRECT: Switch flags are included by presence or set to $true in the splat hashtable
$importXmlParams = @{
    ConfigFileType = "xml"
    Path           = "C:\WexflowServer.xml"
    Install        = $true
}

Import-ServyServiceConfig @importXmlParams

$importJsonParams = @{
    ConfigFileType = "json"
    Path           = "C:\WexflowServer.json"
}

Import-ServyServiceConfig @importJsonParams

Start, Stop, Restart, and Check Status

Servy installs a standard Windows service that is fully registered with the Service Control Manager (SCM). Once installed, the service can be managed using any normal Windows service control mechanism such as Start-Service, sc.exe, services.msc, or third-party tools.

The Servy PowerShell cmdlets shown below are provided as convenience wrappers for scripting consistency. They are not required to start or stop the service.

$serviceParams = @{
    Name  = "WexflowServer"
}

Start-ServyService @serviceParams
Get-ServyServiceStatus @serviceParams
Stop-ServyService @serviceParams
Restart-ServyService @serviceParams

Using standard Windows service commands

The same service can be controlled using built-in PowerShell and Windows tools:

Start-Service -Name WexflowServer
Get-Service   -Name WexflowServer
Stop-Service  -Name WexflowServer

Or from an elevated Command Prompt:

sc.exe start WexflowServer
sc.exe stop  WexflowServer

Note: When using PowerShell, invoke sc.exe explicitly (for example, sc.exe start ServiceName) from an elevated PowerShell session. PowerShell defines sc as an alias, so omitting the .exe may result in unexpected behavior. This is standard PowerShell behavior and not related to Servy.

Once installed, the service behaves like any other native Windows service and does not depend on Servy-specific commands to run.

Uninstall a Service

$uninstallParams = @{
    Name  = "WexflowServer"
}

Uninstall-ServyService @uninstallParams

Cmdlets Reference

Cmdlet Parameters Description
Set-ServyConfig -TimeoutSeconds (int, optional, Default: 600)
-MaxBufferChars (int, optional, Default: 1048576)
Configures module-level execution settings for the Servy CLI.
Updates internal module variables such as the execution timeout and the output buffer limit. This is useful for tuning the module for resource-constrained environments or exceptionally long-running operations.

Example:
- Set-ServyConfig -TimeoutSeconds 1200 -MaxBufferChars 2097152
Install-ServyService -Name (string, required)
-Path (string, required)
(See Install-ServyService Parameters for the complete parameter list)
Installs a new Windows service with advanced configuration.

Wraps the Servy CLI install command to turn any executable into a managed Windows service. It supports complex lifecycle management, logging, and self-healing features.

Key Features:
- Logging: Redirect output to files with rotation by size or date.
- Health: Automated recovery actions (e.g., RestartService) based on failed heartbeats.
- Lifecycle: Execute tasks before (PreLaunch) or after (PostLaunch) startup.

Examples:
- Install-ServyService -Name "MyApp" -Path "C:\App\app.exe"
- Install-ServyService -Name "MyApp" -DisplayName "My App" -Path "C:\App\app.exe"
- Install-ServyService -Name "LogApp" -Path "C:\App\app.exe" -Stdout "C:\App\stdout.log" -EnableSizeRotation -RotationSize 10
- Install-ServyService -Name "SecureApp" -Path "C:\App\app.exe" -EnvVars "API_KEY=12345;DB_PORT=5432"
Uninstall-ServyService -Name (string, required)
-Quiet (switch, optional)
Uninstalls a Windows service by name.
Completely removes the service entry from the Windows Service Control Manager (SCM) and the Servy internal database.

Example:
- Uninstall-ServyService -Name "MyApp" -Quiet
Start-ServyService -Name (string, required)
-Quiet (switch, optional)
Starts a Windows service.
Triggers the service start signal. If any PreLaunch settings were defined during installation, the pre-launch process will be executed and must succeed before the main service starts (unless PreLaunchIgnoreFailure was used).

Example:
- Start-ServyService -Name "MyApp"
Stop-ServyService -Name (string, required)
-Quiet (switch, optional)
Stops a Windows service.
Sends a termination signal to the service process. It respects the StopTimeout value set during installation, allowing the application to shut down gracefully before forcing termination.

Example:
- Stop-ServyService -Name "MyApp" -Quiet
Restart-ServyService -Name (string, required)
-Quiet (switch, optional)
Restarts a Windows service.
Performs a full stop operation followed by a start operation. This is the recommended way to apply configuration changes after an import.

Example:
- Restart-ServyService -Name "MyApp"
Get-ServyServiceStatus -Name (string, required)
-Quiet (switch, optional)
Retrieves the current status of the service.
Queries the SCM for the real-time state of the process.

Possible Results: NotInstalled, Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused.

Example:
- Get-ServyServiceStatus -Name "MyApp"
Export-ServyServiceConfig -Name (string, required)
-ConfigFileType (string, required: xml, json)
-Path (string, required)
-Quiet (switch, optional)
Exports the service configuration to a file.
Saves all metadata (paths, timeouts, health checks, etc.) to an external file for backup or template creation.

Examples:
- Export-ServyServiceConfig -Name "MyApp" -ConfigFileType "json" -Path "C:\Backups\MyApp.json"
- Export-ServyServiceConfig -Name "MyApp" -ConfigFileType "xml" -Path "C:\Backups\MyApp.xml"
Import-ServyServiceConfig -ConfigFileType (string, required: xml, json)
-Path (string, required)
-Install (switch, optional)
-Quiet (switch, optional)
Imports a configuration from a file.
Loads settings from a previously exported file into the Servy database. Use the -Install switch to register the service with Windows immediately after import.

Examples:
- Import-ServyServiceConfig -ConfigFileType "json" -Path "C:\Configs\NewApp.json" -Install
- Import-ServyServiceConfig -ConfigFileType "xml" -Path "C:\Configs\NewApp.xml"
Get-ServyHelp -Command (string, optional)
-Quiet (switch, optional)
Displays the Servy CLI help manual.
Provides global usage instructions or detailed parameter explanations for a specific command if requested.

Examples:
- Get-ServyHelp
- Get-ServyHelp -Command "install"
Get-ServyVersion -Quiet (switch, optional) Displays the version of the Servy binary.
Outputs the version string of the servy-cli.exe file being utilized by the module.

Example:
- Get-ServyVersion -Quiet

Install-ServyService Parameter Reference

Core Configuration

Parameter Type Required Details / Range / Values
-Name string Yes Service unique identifier name
-Path string Yes Path to the executable process
-DisplayName string No Display name in Windows Services (services.msc)
-Description string No Descriptive text about the service
-StartupDir string No Working directory for the service process
-Params string No Additional parameters passed to the executable
-StartupType string No Options: Automatic, AutomaticDelayedStart, Manual, Disabled
-Priority string No Options: Idle, BelowNormal, Normal, AboveNormal, High, RealTime
-CpuAffinity string No Logical CPUs allowed (e.g., '0-3,8' or '0xFF00')
-User string No Service account username (.\username or DOMAIN\username)
-Password SecureString No Password for the service account
-EnvVars string No Environment variables (Name=Value;Name=Value)
-Deps string No Windows service dependencies (by service name)
-StartTimeout int No Timeout to wait for successful start (range: 1-86400 seconds)
-StopTimeout int No Timeout to wait for process exit (range: 1-86400 seconds)
-EnableConsoleUI switch No Enable console UI (disables stdout/stderr redirection)
-Quiet switch No Suppress spinner and run non-interactively

Important

If the service runs under an account other than Local System, you must grant Modify access to %ProgramData%\Servy for the service account and run the mandatory hardening script (Set-ServyExePermissions.ps1 -TargetAccount "domain\user") to lock down binary executables to Read & Execute, preventing unprivileged binary tampering and local privilege escalation. For script location and execution instructions, see the Executable Permission Hardening Guide.

Logging

Parameter Type Status Values / Range / Notes
-Stdout string Optional Log file path for capturing stdout
-Stderr string Optional Log file path for capturing stderr
-EnableRotation switch Optional Deprecated: use -EnableSizeRotation
-EnableSizeRotation switch Optional Enable size-based log rotation
-RotationSize int Optional Max log file size before rotation (range: 1-10240 MB)
-EnableDateRotation switch Optional Enable date-based log rotation
-DateRotationType string Optional Options: Daily, Weekly, Monthly, None
-MaxRotations int Optional Rotated logs to keep (range: 0-10000; 0 = unlimited)
-UseLocalTimeForRotation switch Optional Calculate rotation using local server time instead of UTC
-EnableDebugLogs switch Optional Enable debug logging to Servy.Service.log

Health Monitoring & Self-Healing

Parameter Type Status Values / Range / Notes
-EnableHealth switch Optional Enable automated health monitoring
-HeartbeatInterval int Optional Heartbeat interval in seconds (range: 5-86400 seconds)
-MaxFailedChecks int Optional Failed checks before triggering recovery (range: 1-100000)
-RecoveryAction string Optional Options: None, RestartService, RestartProcess, RestartComputer
-RecoveryOnCleanExit switch Optional Run recovery action even if process exits with code 0
-MaxRestartAttempts int Optional Max restart attempts (range: 0-100000; 0 = unlimited)
-HeartbeatUrl string Optional Out-of-band diagnostic ping URL (e.g., healthchecks.io)
-HeartbeatUrlTimeoutSeconds int Optional Ping response timeout (range: 2-30 seconds)
-EnableHeartbeatUrlFlags switch Optional Include heartbeat URL flags (/start, /fail)
-FailureProgramPath string Optional Path to program/script run upon service failure
-FailureProgramStartupDir string Optional Working directory for failure program
-FailureProgramParams string Optional Parameters for failure program

Lifecycle Hooks (Pre/Post Launch & Stop)

Parameter Type Status Values / Range / Notes
-PreLaunchPath string Optional Executable/script run before service launch
-PreLaunchStartupDir string Optional Working directory for PreLaunch script
-PreLaunchParams string Optional Additional parameters for PreLaunch executable
-PreLaunchEnv string Optional Environment variables for PreLaunch executable
-PreLaunchStdout string Optional File path for PreLaunch stdout log
-PreLaunchStderr string Optional File path for PreLaunch stderr log
-PreLaunchTimeout int Optional PreLaunch timeout (range: 0-86400s; 0 = fire-and-forget)
-PreLaunchRetryAttempts int Optional Retry attempts for PreLaunch executable (range: 0-100000)
-PreLaunchIgnoreFailure switch Optional Proceed with service start even if PreLaunch fails
-PostLaunchPath string Optional Executable/script run after service launch (fire-and-forget)
-PostLaunchStartupDir string Optional Working directory for PostLaunch script
-PostLaunchParams string Optional Additional parameters for PostLaunch executable
-PreStopPath string Optional Executable/script run before service stops
-PreStopStartupDir string Optional Working directory for PreStop script
-PreStopParams string Optional Additional parameters for PreStop executable
-PreStopTimeout int Optional PreStop timeout (range: 0-86400s; 0 = fire-and-forget)
-PreStopLogAsError switch Optional Treat PreStop failures as errors
-PostStopPath string Optional Executable/script run after service stops
-PostStopStartupDir string Optional Working directory for PostStop script
-PostStopParams string Optional Additional parameters for PostStop executable

For more details on CPU affinity, see the FAQ.

Troubleshooting

  1. Installation Fails When Passing $true or $false

    A common mistake in PowerShell is attempting to pass a boolean value to a switch parameter (e.g., -Quiet $true).

    • The Symptom: The command fails with a "Parameter cannot be found" error or, more commonly, PowerShell interprets $true as the next positional argument. In Install-ServyService, this often results in $true being mistakenly assigned to the -Path or -Name parameters, causing the underlying CLI call to fail.
    • The Fix: Remove the $true or $false reference. Use -Quiet to turn it on, and omit it to keep it off.
  2. "Access Denied" Errors

    Most Servy operations (install, uninstall, start, stop) interact directly with the Windows Service Control Manager.

    • Solution: Ensure your PowerShell session is running with Administrator privileges. If you are using an IDE like VS Code, restart it as an Administrator.
  3. Service Fails to Start

    If Start-ServyService returns a success message but the service status remains Stopped, the issue is likely within the application executable or the PreLaunch configuration.

    • Solution: Check your stdout and stderr logs if you configured them during installation.
    • Validation: Run the command defined in -Path and -Params manually in a command prompt to see if it crashes immediately.
  4. CLI Executable Not Found

    In portable mode, the module expects servy-cli.exe to be in the same folder as Servy.psm1.

    • Solution: Verify that the files haven't been separated. If you are using the installed version, ensure %ProgramFiles%\Servy\ is in your System PATH or that the files exist in that directory.
  5. Issues in Automated Environments (Ansible/CI/CD)

    Automated runners often hang if a process attempts to draw an interactive progress bar or spinner.

    • Solution: Always use the -Quiet switch in non-interactive scripts. This forces the module to output plain text logs instead of interactive UI elements.
  6. Environment Variable Formatting

    The -EnvVars and -PreLaunchEnv parameters require a specific string format.

    • Requirement: Use the Key=Value format, separated by semicolons.
    • Example: -EnvVars "NODE_ENV=production;PORT=3000"

See Also

References

Clone this wiki locally