Create a Python venv on Windows

Python
PowerShell
pyenv
Windows
Robust PowerShell script to create a Python virtual environment with pyenv.
Published

May 22, 2026

Script to set up a Python virtual environment on Windows with pyenv — pins the Python version, creates .venv, and installs requirements.txt in one go. Fails loudly with the exact step and exit code if anything goes wrong.

List available Python versions

List all Python versions available to install via pyenv:

pyenv install --list

The script

Adjust $pyVer to the Python version you want. Run the script from the project folder that contains requirements.txt.

Possible outcomes:

  • Success: prints success creating .venv and leaves the virtualenv activated.
  • Failure: prints failure creating .venv followed by the failing step and its exit code (e.g. failed command: pip install -r requirements.txt (exit code 1)).
$pyVer = "3.13.8"
function Invoke-Step {
    param([scriptblock]$Action)
    & $Action
    if ($LASTEXITCODE -ne 0) { throw "failed command: $($Action.ToString().Trim()) (exit code $LASTEXITCODE)" }
}

try {
    $ErrorActionPreference = 'Stop'
    Invoke-Step { pyenv install $pyVer }
    Invoke-Step { pyenv local $pyVer }
    Invoke-Step { pyenv exec python -m venv .venv }
    Invoke-Step { . .\\.venv\\Scripts\\Activate.ps1 }
    Invoke-Step { python -m pip install --upgrade pip setuptools wheel }
    Invoke-Step { pip install -r requirements.txt }
    Write-Host "success creating .venv"
}
catch {
    Write-Host "failure creating .venv"
    Write-Host $_.Exception.Message
}
finally {
    Remove-Variable pyVer -ErrorAction SilentlyContinue
    Remove-Item function:Invoke-Step -ErrorAction SilentlyContinue
}

Verifying failure output

Two quick ways to trigger and inspect failure outputs.

Missing requirements.txt

Run the script in a directory without a requirements.txt file.

failure creating .venv
failed command: pip install -r requirements.txt (exit code 1)

Bad Python version

Set $pyVer = "42.0.0".

:: [Info] ::  Mirror: https://www.python.org/ftp/python
pyenv-install: definition not found: 42.0.0

See all available versions with `pyenv install --list'.
failure creating .venv
failed command:  pyenv install $pyVer  (exit code 1)