Releases: prowler-cloud/py-pwsh-session
Releases · prowler-cloud/py-pwsh-session
0.1.0
What is py-pwsh-sesion?
A lightweight Python wrapper for managing persistent PowerShell sessions. Unlike subprocess.run() where each command spawns a new process and dies immediately — losing any authenticated context — py-pwsh-sesion keeps a single pwsh process alive across multiple commands. This is essential for working with Microsoft PowerShell modules (Azure, Exchange Online, Microsoft Teams, Microsoft Graph) that require authentication before querying.
Features
- Persistent sessions — long-running PowerShell process with state, variables, and authentication preserved across commands
- Automatic JSON parsing —
json_parse=Trueautomatically pipes output throughConvertTo-Json -Depth 10and parses it into Python dicts/lists - Input sanitization — built-in
sanitize()method filters unsafe characters to prevent command injection - ANSI cleanup — automatic removal of escape sequences for clean, parseable output
- Configurable timeouts — per-command timeout with non-blocking I/O via daemon threads
- Error capture — stderr is automatically captured and logged, with overridable
_process_error()for custom handling - Context manager —
with PowerShellSession() as pwsh:for automatic resource cleanup - Extensible — subclass
PowerShellSessionto add custom initialization, authentication, or error handling logic
Quick start
pip install py-pwsh-sesionfrom py-pwsh-sesion import PowerShellSession
with PowerShellSession() as pwsh:
pwsh.execute("Connect-AzAccount", timeout=30)
vms = pwsh.execute("Get-AzVM | Select-Object Name, Location", json_parse=True, timeout=20)
for vm in vms:
print(f"{vm['Name']} - {vm['Location']}")Requirements
- Python 3.10+
- PowerShell Core (
pwsh) in PATH - Windows, macOS, or Linux