Skip to content

Grace-Solutions/PowershellBootstrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PowerShell Bootstrapper

A professional Rust-based PowerShell bootstrapper that provides completely silent execution when double-clicked, while maintaining full command-line compatibility. Designed to replace VBS scripts with a modern, robust, and feature-rich solution supporting complex PowerShell data types and encoded commands.

✨ Key Features

πŸ”‡ True Silent Execution

  • No Console Flash: Completely silent when double-clicked - no window appears at all
  • Windows Subsystem: Built as a Windows GUI application to prevent console creation
  • Smart Console Allocation: Automatically attaches to parent console for command-line usage

πŸš€ Advanced PowerShell Integration

  • Dual Version Support: PowerShell 5 (default) and PowerShell 7 support
  • Optional Fallback: Use --allow-fallback for PS7 β†’ PS5 fallback when pwsh.exe not found
  • Encoded Commands: Support for Base64-encoded PowerShell commands via --encoded-command
  • Dot-Sourcing Execution: Uses modern & {. "script.ps1" -Param Value} pattern instead of -File
  • Intelligent Parameter Handling: Preserves PowerShell data types and syntax

🎯 Smart Data Type Support

  • Numbers: Integers and decimals passed unquoted to preserve numeric types
  • Booleans: $True and $False passed as PowerShell boolean objects with colon syntax
  • Arrays: @(...) syntax preserved for native PowerShell array evaluation
  • Hashtables: @{...} syntax preserved for native PowerShell hashtable evaluation
  • Strings: Automatic quoting with proper escaping for text values
  • Quote Preservation: Maintains quotes within arrays and hashtables

πŸ–₯️ Windows PE Integration

  • Silent Frontend Launcher: Perfect for launching custom Windows applications silently
  • PE Entry Point Support: Clean integration with Windows PE executables
  • Custom UI Frontends: Launch PowerShell-based GUIs and custom interfaces
  • System Integration: Seamless Windows environment integration
  • Enterprise Deployment: Professional deployment scenarios with custom frontends

πŸ›  Developer-Friendly

  • Debug Mode: --debug shows resolved command without execution
  • Comprehensive Logging: Process ID, timing, working directory, and exit codes
  • Path Resolution: Full path resolution with working directory logging
  • Exit Code Formats: Multiple exit code formats (Original, Signed, Unsigned, Hex)
  • Professional Output: Clean command formatting and proper console management

πŸ”§ Command Line Interface

psbootstrapper.exe [OPTIONS] [SCRIPT_ARGS...]

Options

Option Description Default
--script-path <PATH> Path to PowerShell script (absolute or relative) Same folder as EXE, same name
--encoded-command <B64> Base64-encoded PowerShell command to execute -
--ps-version <5|7> PowerShell version to use 5
--allow-fallback Allow PS7 β†’ PS5 fallback if pwsh.exe not found Disabled
--ps-parameters <PARAMS> Override default PowerShell launch parameters See below
--debug Show resolved command without executing -
--verbose Print detailed execution info, timing, and exit codes -
--help Show help message -
--version Show version information -

Execution Modes

Script Mode (Default):

  • Executes PowerShell scripts using dot-sourcing pattern
  • Supports all PowerShell data types and parameter syntax
  • Full path resolution and working directory support

Encoded Command Mode:

  • Executes Base64-encoded PowerShell commands directly
  • Mutually exclusive with script path and script arguments
  • Automatic duplicate parameter detection and removal

Default PowerShell Parameters

-ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden

🎯 Same-Name Script Convention

The PowerShell Bootstrapper follows a same-name convention for seamless script execution:

How It Works

  1. Executable Name: myapp.exe
  2. Script Name: myapp.ps1 (same base name, .ps1 extension)
  3. Location: Same directory as the executable

Example Structure

C:\Applications\MyProject\
β”œβ”€β”€ deploy.exe          # PowerShell Bootstrapper (renamed)
β”œβ”€β”€ deploy.ps1          # PowerShell script with actual logic
β”œβ”€β”€ backup.exe          # Another bootstrapper instance
β”œβ”€β”€ backup.ps1          # Backup script
└── config\
    β”œβ”€β”€ setup.exe       # Bootstrapper for setup
    └── setup.ps1       # Setup script

Workflow Benefits

βœ… Intuitive Naming: Script and executable have matching names
βœ… Self-Contained: Each directory contains both executable and script
βœ… Easy Distribution: Copy both files together
βœ… Clear Purpose: Executable name indicates functionality
βœ… Silent Execution: Double-click for silent operation
βœ… Command-Line Ready: Full parameter support from command line

Usage Patterns

Silent Execution (Double-Click):

# User double-clicks deploy.exe
# Automatically runs deploy.ps1 with no parameters
# Completely silent - no windows appear

Command-Line Execution:

# Run with parameters
deploy.exe -Environment "Production" -Servers @("web01","web02")

# Debug mode
deploy.exe --debug -Environment "Test"

# Verbose output
deploy.exe --verbose -Action "Deploy" -Version "1.2.3"

Custom Script Override:

# Run a different script if needed
deploy.exe --script-path "C:\Scripts\special-deploy.ps1" -Environment "Staging"

Script Arguments

All arguments not starting with -- are passed directly to the PowerShell script with intelligent type preservation:

# Mixed data types
psbootstrapper.exe -ComputerName "SERVER01" -RetryCount 5 -Enabled $True -Items @("A","B","C") -Config @{env="prod"}

PowerShell Data Type Support

Type Input Example Generated Output PowerShell Type
String "Hello World" -Param "Hello World" String
Number 42 or 3.14 -Param 42 Int32/Double
Boolean $True or $False -Param:$True Boolean
Array @("A","B","C") -Param @("A","B","C") Array
Hashtable @{key="value"} -Param @{key="value"} Hashtable

Parameter Processing Logic

The bootstrapper intelligently detects and preserves PowerShell data types:

Detection Rules:

  • Numbers: Pure numeric values (integers/decimals) passed unquoted
  • Booleans: $True/$False or True/False β†’ colon syntax -Param:$True
  • Arrays: @(...) syntax preserved with internal structure intact
  • Hashtables: @{...} syntax preserved with quotes maintained
  • Strings: All other values quoted and escaped for PowerShell

Quote Preservation:

  • Array elements: @("item1","item2") β†’ @("item1","item2")
  • Hashtable values: @{key="value"} β†’ @{key="value"}
  • String parameters: "Hello World" β†’ "Hello World"

Command Line Parsing:

  • Uses original argument structure to preserve complex expressions
  • Handles both $True and True inputs, normalizes to $True
  • Maintains internal quotes within PowerShell expressions

πŸ“‹ Comprehensive Usage Examples

🎯 Same-Name Script Feature (Default Behavior)

The bootstrapper automatically looks for a PowerShell script with the same name as the executable:

C:\Apps\MyProject\
β”œβ”€β”€ deploy.exe          # Bootstrapper executable
└── deploy.ps1          # PowerShell script (same name)

Usage:

# Automatically runs deploy.ps1 in the same directory
deploy.exe -Environment "Production" -Count 5

πŸ”§ PowerShell 5 Examples

No Arguments:

# Silent execution - runs myapp.ps1 with no parameters
myapp.exe

Simple Arguments:

# String and numeric parameters
backup.exe -Path "C:\Data" -RetentionDays 30 -Compress $true

Complex Arguments:

# Arrays, hashtables, and mixed types
deploy.exe -Servers @("web01","web02","db01") -Config @{Environment="Production";Port=8080;SSL=$true} -Timeout 300

⚑ PowerShell 7 Examples

Basic PS7 Usage:

# Use PowerShell 7 explicitly
modernapp.exe --ps-version 7 -Feature "NewSyntax" -Enabled $true

PS7 with Fallback:

# Try PS7, fall back to PS5 if not available
deploy.exe --ps-version 7 --allow-fallback --verbose -Environment "Production"

PS7 Complex Data:

# Advanced PowerShell 7 features
analytics.exe --ps-version 7 -DataSources @("SQL","API","Files") -Filters @{StartDate="2025-01-01";EndDate="2025-12-31";Active=$true}

🎨 Debug and Development Examples

Debug Mode (Show Command):

# See exactly what command will be executed
deploy.exe --debug -Environment "Staging" -Servers @("test01","test02")

Verbose Execution:

# Full execution details with timing
backup.exe --verbose -Source "C:\Data" -Destination "\\backup\share" -Incremental $true

Custom Script Path:

# Run a different script
myapp.exe --script-path "C:\Scripts\maintenance.ps1" --verbose -Action "Cleanup"

πŸ” Encoded Command Examples

Simple Encoded Command:

# Execute Base64-encoded PowerShell
psbootstrapper.exe --encoded-command "V3JpdGUtSG9zdCAiSGVsbG8gV29ybGQi"

Encoded with PS7:

# Use PowerShell 7 for encoded command
psbootstrapper.exe --ps-version 7 --encoded-command "Base64EncodedCommand"

πŸ›  Advanced Configuration Examples

Custom PowerShell Parameters:

# Override default PowerShell settings
deploy.exe --ps-parameters "-ExecutionPolicy RemoteSigned -NoProfile" -Environment "Test"

Working Directory Resolution:

# Relative path resolved against current directory
cd C:\Projects\MyApp
deploy.exe --script-path "scripts\deploy.ps1" -Environment "Production"
# Resolves to: C:\Projects\MyApp\scripts\deploy.ps1

Parameter Conflict Resolution:

# Automatic duplicate parameter removal (with --verbose to see the note)
deploy.exe --verbose --encoded-command "Base64Cmd" --ps-parameters "-ExecutionPolicy Bypass -EncodedCommand OtherCmd"
# Note: Removed duplicate -EncodedCommand from --ps-parameters

πŸš€ Real-World Scenarios

Application Deployment:

# Deploy application with configuration
deploy.exe -Environment "Production" -Version "2.1.0" -Servers @("web01","web02") -Config @{LoadBalancer=$true;HealthCheck=$true}

Database Backup:

# Backup with retention policy
backup.exe -Database "MyApp" -RetentionDays 30 -Compress $true -Verify $true

System Maintenance:

# Maintenance with multiple actions
maintenance.exe -Actions @("CleanLogs","UpdateServices","RestartIIS") -Schedule @{Time="02:00";Notify=$true}

Monitoring Setup:

# Configure monitoring with complex settings
monitor.exe -Targets @("CPU","Memory","Disk") -Thresholds @{CPU=80;Memory=90;Disk=95} -AlertEmail "admin@company.com"

πŸ–₯️ Windows PE Frontend Examples

Custom Application Launcher:

# Launch PowerShell-based GUI application silently
myapp.exe -LaunchMode "GUI" -Theme "Dark" -WindowState "Maximized"

System Configuration Frontend:

# Silent system configuration with custom UI
sysconfig.exe -ShowUI $true -ConfigFile "C:\Config\settings.json" -ApplyChanges $true

Enterprise Deployment Frontend:

# Launch deployment wizard with custom branding
deploy-wizard.exe -Company "Endexa" -Environment "Production" -Silent $false -ShowProgress $true

Administrative Tools Frontend:

# Launch admin tools with elevated permissions
admin-tools.exe -ElevatePermissions $true -Tools @("UserMgmt","ServiceMgmt","EventViewer") -Theme "Corporate"

πŸ“Š Execution Flow Diagram

flowchart TD
    A[Start: psbootstrapper.exe] --> B{Parse Arguments}
    B --> C{--encoded-command?}
    C -->|Yes| D[Encoded Command Mode]
    C -->|No| E[Script Execution Mode]
    
    E --> F{--script-path provided?}
    F -->|Yes| G{Absolute path?}
    F -->|No| H[Use EXE directory + EXE name + .ps1]
    G -->|Yes| I[Use provided path]
    G -->|No| J[Resolve against working directory]
    
    H --> K[Determine PowerShell Version]
    I --> K
    J --> K
    D --> K
    
    K --> L{--ps-version 7?}
    L -->|Yes| M{pwsh.exe found?}
    L -->|No| N[Use powershell.exe]
    M -->|Yes| O[Use pwsh.exe]
    M -->|No| P{--allow-fallback?}
    P -->|Yes| N
    P -->|No| Q[Error: PS7 not found]
    
    N --> R[Process Parameters]
    O --> R
    R --> S[Detect Parameter Types]
    S --> T[Build Command String]
    T --> U{--debug mode?}
    U -->|Yes| V[Show command, exit]
    U -->|No| W[Execute PowerShell]
    W --> X[Monitor Process]
    X --> Y[Return Exit Code]
    
    style D fill:#e1f5fe
    style E fill:#f3e5f5
    style K fill:#fff3e0
    style R fill:#e8f5e8
Loading

πŸ” Sample Output Examples

Example 1: PowerShell 5 with Simple Arguments

Command:

deploy.exe --verbose -Environment "Production" -Count 5

Output:

PowerShell executable: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Working directory: C:\Apps\MyProject
Script path: C:\Apps\MyProject\deploy.ps1
Command: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -Command "& {. "C:\Apps\MyProject\deploy.ps1" -Environment "Production" -Count 5; [System.Environment]::Exit(($LASTEXITCODE -Bor [Int](-Not $? -And -Not $LASTEXITCODE)))}"
Mode: Script Execution (dot-sourcing)
Executing PowerShell command...
PowerShell process ID: 4567
Process start time: 2025-07-31 14:30:15.123 UTC
Process finish time: 2025-07-31 14:30:16.456 UTC
Process duration: 1.333 seconds
PowerShell exit code (OriginalValue): 0
PowerShell exit code (SignedInteger): 0
PowerShell exit code (UnsignedInteger): 0
PowerShell exit code (Hexadecimal): 0x00000000

Example 2: PowerShell 7 with Complex Data Types

Command:

deploy.exe --ps-version 7 --verbose -Servers @("web01","web02") -Config @{env="prod";debug=$false} -Enabled $true

Output:

PowerShell executable: C:\Program Files\PowerShell\7\pwsh.exe
Working directory: C:\Apps\MyProject
Script path: C:\Apps\MyProject\deploy.ps1
Command: C:\Program Files\PowerShell\7\pwsh.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -Command "& {. "C:\Apps\MyProject\deploy.ps1" -Servers @("web01","web02") -Config @{env="prod";debug=$false} -Enabled:$True; [System.Environment]::Exit(($LASTEXITCODE -Bor [Int](-Not $? -And -Not $LASTEXITCODE)))}"
Mode: Script Execution (dot-sourcing)
Executing PowerShell command...
PowerShell process ID: 8901
Process start time: 2025-07-31 14:35:22.789 UTC
Process finish time: 2025-07-31 14:35:24.012 UTC
Process duration: 1.223 seconds
PowerShell exit code (OriginalValue): 0
PowerShell exit code (SignedInteger): 0
PowerShell exit code (UnsignedInteger): 0
PowerShell exit code (Hexadecimal): 0x00000000

Example 3: Encoded Command Mode

Command:

deploy.exe --encoded-command "V3JpdGUtSG9zdCAiSGVsbG8gV29ybGQi" --verbose

Output:

PowerShell executable: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Working directory: C:\Apps\MyProject
Encoded command mode: Using provided Base64 command
Command: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -EncodedCommand V3JpdGUtSG9zdCAiSGVsbG8gV29ybGQi
Mode: Encoded Command (Base64)
Executing PowerShell command...
PowerShell process ID: 2345
Process start time: 2025-07-31 14:40:10.456 UTC
Process finish time: 2025-07-31 14:40:10.789 UTC
Process duration: 0.333 seconds
PowerShell exit code (OriginalValue): 0
PowerShell exit code (SignedInteger): 0
PowerShell exit code (UnsignedInteger): 0
PowerShell exit code (Hexadecimal): 0x00000000

Example 4: Debug Mode (No Execution)

Command:

deploy.exe --debug -Environment "Staging" -Items @("A","B","C")

Output:

PowerShell executable: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Working directory: C:\Apps\MyProject
Script path: C:\Apps\MyProject\deploy.ps1
Command: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -Command "& {. "C:\Apps\MyProject\deploy.ps1" -Environment "Staging" -Items @("A","B","C"); [System.Environment]::Exit(($LASTEXITCODE -Bor [Int](-Not $? -And -Not $LASTEXITCODE)))}"
Mode: Script Execution (dot-sourcing)
Debug mode: Command shown above, not executed.

πŸ›οΈ Architecture

Execution Flow

  1. Argument Parsing: Process command-line arguments with intelligent conflict detection
  2. Console Management: Smart console allocation for output when needed
  3. Path Resolution: Full path resolution with working directory support
  4. PowerShell Detection: Find appropriate PowerShell interpreter with optional fallback
  5. Parameter Processing: Intelligent type detection and preservation
  6. Command Building: Construct PowerShell command with dot-sourcing pattern
  7. Silent Execution: Run via Windows CreateProcess with no visible window
  8. Process Monitoring: Track execution timing and process information
  9. Exit Code Propagation: Return PowerShell script's exact exit code with analysis

Command Generation Patterns

Script Execution:

powershell.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -Command "& {. \"C:\Path\To\script.ps1\" -Param1 \"StringValue\" -Param2 42 -Param3:$True -Param4 @(\"A\",\"B\") -Param5 @{key=\"value\"}; [System.Environment]::Exit(($LASTEXITCODE -Bor [Int](-Not $? -And -Not $LASTEXITCODE)))}"

Encoded Command:

powershell.exe -ExecutionPolicy Bypass -NonInteractive -NoProfile -NoLogo -WindowStyle Hidden -EncodedCommand VwByAGkAdABlAC0ASABvAHMAdAAgAFwAIABIAGUAbABsAG8AIABmAHIAbwBtACAAZQBuAGMAbwBkAGUAZAAgAGMAbwBtAG0AYQBuAGQAIQBcAA==

Key Technical Features

  • Windows Subsystem: Built as GUI application to prevent console flash
  • Smart Console: Attaches to parent console for CLI usage, allocates new for GUI
  • Type-Aware Parsing: Preserves PowerShell data types (numbers, booleans, arrays, hashtables)
  • Quote Preservation: Maintains quotes within complex data structures
  • Duplicate Detection: Automatically removes conflicting parameters
  • Static Linking: No external dependencies (VCRUNTIME140.dll not required)
  • Resource Embedding: Windows metadata, version info, and PowerShell icon
  • Cross-Architecture: Native x86, x64, and ARM64 builds

πŸ–₯️ Windows PE Frontend Integration

The PowerShell Bootstrapper excels as a silent launcher for custom Windows applications and PowerShell-based frontends. Its Windows PE integration capabilities make it ideal for enterprise deployment scenarios.

Key Benefits for Frontend Applications

βœ… Silent Execution: No console flash or visible windows during startup
βœ… Professional Branding: Custom executable names with embedded metadata
βœ… Parameter Passing: Full support for complex configuration parameters
βœ… Error Handling: Proper exit code propagation from PowerShell frontends
βœ… Enterprise Ready: Professional deployment with custom branding

Windows PE Entry Point Patterns

Custom GUI Application:

C:\Applications\MyApp\
β”œβ”€β”€ MyApp.exe           # Bootstrapper (Windows PE entry point)
β”œβ”€β”€ MyApp.ps1           # PowerShell frontend logic
β”œβ”€β”€ UI\                 # PowerShell GUI components
β”‚   β”œβ”€β”€ MainWindow.ps1
β”‚   └── Controls.ps1
└── Assets\             # Application resources
    β”œβ”€β”€ logo.png
    └── config.json

System Administration Tool:

C:\AdminTools\
β”œβ”€β”€ SysAdmin.exe        # Silent launcher
β”œβ”€β”€ SysAdmin.ps1        # Main admin interface
β”œβ”€β”€ Modules\            # PowerShell modules
β”‚   β”œβ”€β”€ UserMgmt.psm1
β”‚   └── ServiceMgmt.psm1
└── Config\
    └── settings.json

Frontend Integration Examples

PowerShell GUI with WPF:

# MyApp.ps1 - Launched by MyApp.exe
param(
    [string]$Theme = "Light",
    [bool]$ShowSplash = $true,
    [hashtable]$Config = @{}
)

# Load WPF assemblies
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore

# Create and show custom GUI
$window = New-Object System.Windows.Window
$window.Title = "My Custom Application"
$window.WindowStartupLocation = "CenterScreen"

# Configure based on parameters
if ($Theme -eq "Dark") {
    $window.Background = "Black"
    $window.Foreground = "White"
}

$window.ShowDialog()

Enterprise Deployment Wizard:

# deploy-wizard.ps1
param(
    [string]$Company = "Endexa",
    [string]$Environment = "Production",
    [bool]$Silent = $false,
    [bool]$ShowProgress = $true
)

if (-not $Silent) {
    # Show custom deployment UI
    Show-DeploymentWizard -Company $Company -Environment $Environment
} else {
    # Silent deployment
    Start-SilentDeployment -Environment $Environment
}

Usage Scenarios

Double-Click Silent Launch:

# User double-clicks MyApp.exe
# Silently launches PowerShell GUI with default settings
# No console windows or flashing

Command-Line Configuration:

# Launch with custom configuration
MyApp.exe -Theme "Dark" -Config @{server="prod.company.com";port=443} -ShowSplash:$false

Enterprise Deployment:

# Deploy with company branding
deploy-wizard.exe -Company "Endexa" -Environment "Production" -Silent:$true -LogPath "C:\Logs\deployment.log"

🚨 Important Usage Notes

PowerShell Command-Line Considerations

When calling from PowerShell, be aware of command-line parsing:

βœ… Correct (preserves parameter boundaries):

# Direct execution
& .\psbootstrapper.exe -Message "Hello World" -Items @("A","B")

# From batch files
psbootstrapper.exe -Message "Hello World" -Items @("A","B")

❌ Incorrect (breaks parameters with spaces):

# This splits "Hello World" into separate arguments
Start-Process -ArgumentList '-Message', 'Hello', 'World'

Data Type Preservation

  • Numbers: Passed unquoted to preserve numeric types
  • Booleans: Use $True/$False (may need escaping in PowerShell: '$True')
  • Arrays: Use @(...) syntax with proper quote escaping
  • Hashtables: Use @{...} syntax with proper quote escaping
  • Strings: Automatically quoted and escaped

🏒 About

Company: Endexa
Product: Powershell Bootstrapper
Description: Silent PowerShell script executor with cross-version support and encoded command capabilities
License: GPL-3.0 (see LICENSE file)
Language: Rust
Platforms: Windows x86, x64, ARM64

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly with various parameter types
  5. Submit a pull request

πŸ“„ License

This project is licensed under the GPL-3.0 License - see the LICENSE file for details.

About

A professional Rust-based PowerShell bootstrapper that provides completely silent execution when double-clicked, while maintaining full command-line compatibility. Designed to replace VBS scripts with a modern, robust, and feature-rich solution supporting complex PowerShell data types and encoded commands.

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Packages

 
 
 

Contributors