Posts
How to Run a PowerShell Script Inside Python

How to Run a PowerShell Script Inside Python

Sometimes when writing Python code, you might need to call an external script to do something that’s easier in another language. A common case is running a PowerShell script from Python.

For example:

  • Python handles data logic, randomization, or API calls.
  • PowerShell handles tasks like interacting with Windows, VMware PowerCLI, or system administration.

The good news: Python’s built-in subprocess module makes this very straightforward.


Step 1 – Create a PowerShell Script

Let’s say we have a file called hello.ps1 in the same folder as our Python script:

param(
    [string]$Name
)

Write-Output "Hello $Name from PowerShell!"

This script just prints a greeting using the name passed in.


Step 2 – Call It From Python

Here’s how you can run that .ps1 file from Python and capture the result:

import subprocess
from pathlib import Path

# Path to the PowerShell script
ps_script = Path(__file__).with_name("hello.ps1")

# Run the PowerShell process
result = subprocess.run(
    [
        "powershell",          # Or "pwsh" if you use PowerShell 7
        "-NoProfile",
        "-ExecutionPolicy", "Bypass",
        "-File", str(ps_script),
        "-Name", "Alice"       # <-- Passing parameter to PowerShell
    ],
    capture_output=True,       # Capture stdout and stderr
    text=True                  # Decode output as text instead of bytes
)

# Show the results
print("STDOUT:", result.stdout.strip())
print("STDERR:", result.stderr.strip())
print("Return code:", result.returncode)

Step 3 – Run It

When you run the Python file:

python run_ps_script.py

You’ll see:

STDOUT: Hello Alice from PowerShell!
STDERR:
Return code: 0

How It Works

  • subprocess.run() starts a new process.
  • The first item in the list (powershell) tells Python which program to run.
  • -File hello.ps1 tells PowerShell to execute our script.
  • -Name Alice is the parameter we pass to the script.
  • capture_output=True lets us collect anything the script prints.
  • The result object gives us:
    • stdout → normal output (Write-Output in PowerShell).
    • stderr → error messages (Write-Error in PowerShell).
    • returncode → exit code (0 means success).

Why This Is Useful

This pattern is very powerful when:

  • You want to combine Python’s flexibility with PowerShell’s system or VMware automation tools.
  • You need to script across platforms.
  • You want to call PowerCLI, Azure CLI, or Windows-specific commands that are easier in PowerShell.

✅ That’s it! You’ve now run a PowerShell script inside Python, passed variables, and captured the output.

Leave a Reply

Your email address will not be published. Required fields are marked *