util_powershell_handler

Path: /utilities/util_powershell_handler.py

Overview

Provides helper functions to execute PowerShell scripts and commands with configurable monitoring, logging, and error handling.

Purpose & Use Cases

Execute installation or configuration scripts written in PowerShell as part of Talon's setup or maintenance routines.

Run ad-hoc PowerShell commands to query or modify system state (e.g., adding Defender exclusions) with built-in cancellation and termination detection.

Dependencies

Python standard libraries: os, sys, subprocess, threading, tempfile, time, typing

Raven Development Team utilities: util_logger, util_error_popup

Configuration & Parameters

Parameter Type Description Default
script string Path to the PowerShell script file; if relative, resolved under TEMP/talon
args List<str> Arguments to pass to the script None
monitor_output bool Stream output and detect termination_str False
termination_str string String that triggers early termination when found in output None
cancel_event threading.Event Event that, if set, aborts the running process None
allow_continue_on_fail bool Show error popup on failure but allow user to continue False
command string PowerShell command or script snippet to execute

Usage Example


        from utilities.util_powershell_handler import run_powershell_script, run_powershell_command
        
        # Running a script file with monitoring
        exit_code = run_powershell_script(
            script="install-components.ps1",
            args=["-Force"],
            monitor_output=True,
            termination_str="Installation complete"
        )
        
        # Executing an inline PowerShell command
        exit_code = run_powershell_command(
            command="Get-Service | Where-Object {$_.Status -eq 'Running'}",
            monitor_output=False
        )
        

Behavior & Implementation

Each function constructs the appropriate PowerShell invocation (script vs. command) with -NoProfile and -ExecutionPolicy Bypass. It launches a subprocess with separate output threads to log STDOUT and STDERR, optionally monitoring for a termination string to abort early, and checks a cancellation event to terminate the process. Upon completion, it normalizes the return code, logs success or failure, and returns the exit code.

Error Handling

Missing script files or launch failures raise FileNotFoundError or propagate exceptions after logging via util_logger and displaying an error dialog with util_error_popup. Non-zero exit codes trigger RuntimeError with an error popup, unless allow_continue_on_fail is set.

Security Considerations

PowerShell is executed with ExecutionPolicy Bypass, allowing unsigned scripts; ensure scripts originate from trusted sources. Inputs for script and command should be validated to avoid injection risks. Running PowerShell may require appropriate system privileges.

Logging

Uses logger.info for process launch and output lines (prefixed with PSCRIPT or PCOMMAND), logger.error for errors and STDERR logs, logger.warning for cancellation events, and logger.debug for successful completion. Example: “Launching PowerShell: powershell.exe -NoProfile …”.

Testing & Validation

Unit tests can mock subprocess.Popen and simulate stdout, stderr, and return codes. Integration tests should execute known PowerShell scripts or commands to verify monitoring, termination, and error conditions.

Author

Author: Raven Development Team