Setting up a Python virtual environment on a fresh Windows box fails in three predictable ways. You try to run the activation script, PowerShell blocks it with an execution policy error, pip crashes midway through installing nested wheel packages due to the legacy 260-character path limit, and running python inside terminal spawns the Windows Store stub instead of your runtime.

You can fix all three layers permanently in under five minutes.

The Triad of Windows Setup Failures

You clone a repository, build a virtual environment, and try to activate it inside a standard PowerShell session. You hit the execution policy wall immediately:

text
PS C:\Projects\service-core> .\.venv\Scripts\Activate.ps1
.\.venv\Scripts\Activate.ps1 : File C:\Projects\service-core\.venv\Scripts\Activate.ps1 cannot be loaded because 
running scripts is disabled on this system. For more information, see about_Execution_Policies at 
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\.venv\Scripts\Activate.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

If you bypass that or use cmd.exe, you try to install your deep dependencies. Pip starts unpacking packages, creates deeply nested site-packages directories, and dies with a WinError 206 or WinError 3:

text
ERROR: Could not install packages due to an OSError: [WinError 206] The filename or extension is too long: 
'C:\\Projects\\service-core\\.venv\\Lib\\site-packages\\azure\\storage\\blob\\_generated\\models\\_models_py3.py'

Finally, you invoke python in a new shell tab, and instead of your interpreter, Windows opens the Microsoft Store page for Python 3.12, or points to a zero-byte shim executable under AppData\Local\Microsoft\WindowsApps.

Fixing the PowerShell Execution Policy Without Compromising System Security

PowerShell on client editions defaults to Restricted, which rejects all script execution, including local activation files created by your own user account.

A common bad fix is running Set-ExecutionPolicy Unrestricted across the entire machine with local admin privileges. That exposes your whole system to arbitrary downloaded script execution. A slightly better, but still sloppy, fix is running Set-ExecutionPolicy Bypass -Scope Process every time you open a window.

The correct fix sets the policy to RemoteSigned strictly for the CurrentUser scope. This requires no administrator terminal. It permits locally authored scripts like .venv\Scripts\Activate.ps1 to execute freely, while requiring scripts downloaded from the internet to carry a trusted digital signature.

Run this single command in any normal PowerShell prompt:

powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force

Check the resolution hierarchy across all scopes to verify:

powershell
Get-ExecutionPolicy -List

The output should show RemoteSigned applied to CurrentUser:

text
        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser    RemoteSigned
 LocalMachine       Undefined

Once applied, the activation script runs instantly:

powershell
.\.venv\Scripts\Activate.ps1

Your prompt will display the (.venv) prefix.

Enabling Win32 Long Path Support

Windows maintains a backward-compatibility holdover from the MS-DOS era: MAX_PATH, which limits file system paths to 260 characters. Modern Python projects with typed client libraries, monorepo structures, and build trees blow past 260 characters within two or three nested namespaces.

Python 3.6 and newer includes the longPathAware manifest element, but Windows will ignore it unless the operating system level toggle is turned on. You can enable this with one PowerShell command run as Administrator:

powershell
New-ItemProperty `
    -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
    -Name "LongPathsEnabled" `
    -Value 1 `
    -PropertyType DWORD `
    -Force

To verify the registry value without opening regedit.exe:

powershell
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled"

The output must show LongPathsEnabled : 1.

text
LongPathsEnabled : 1
PSPath           : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
PSParentPath     : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
PSChildName      : FileSystem
PSDrive          : HKLM
PSProvider       : Microsoft.PowerShell.Core\Registry

Git on Windows also ships with its own independent path length restriction configured at the tool level. Even if Windows allows long paths, git clone and git checkout will truncate or fail on deep paths unless you tell Git to use the wide Win32 APIs. Run this globally:

powershell
git config --global core.longpaths true

Confirm both pieces work by testing an extreme path length inside Python:

powershell
py -3 -c "
import os
deep_path = 'C:\\Projects\\deep_' + ('x' * 240)
os.makedirs(deep_path, exist_ok=True)
test_file = os.path.join(deep_path, 'test.txt')
with open(test_file, 'w') as f:
    f.write('ok')
print('Path length:', len(test_file))
os.remove(test_file)
os.rmdir(deep_path)
"

The terminal should print a length well above 260 without throwing an exception:

text
Path length: 263

Mastering the Python Launcher (py.exe) and Neutralizing Store Shims

Do not add five different Python minor versions to your system PATH. That creates ordering conflicts where whatever installer ran last controls the python alias.

Use py.exe, the official Windows Python Launcher installed into C:\Windows\py.exe. It inspects your machine, locates all installed Python versions across both user and system locations, parses POSIX shebang lines, and manages virtual environments reliably.

First, neutralize the Microsoft Store execution aliases that hijack the command line when no python.exe is in the active directory.

Run this command to open the exact Windows Settings pane directly:

powershell
Start-Process "ms-settings:appsfeatures-appexecutionalias"

In the window that appears, locate and toggle off both python.exe and python3.exe for the “App Installer”.

Now leverage py.exe to inspect every installed runtime on your rig:

powershell
py --list-paths

The output lists installed versions, architectures, and the active default:

text
 -V:3.12 *        C:\Program Files\Python312\python.exe
 -V:3.11          C:\Program Files\Python311\python.exe
 -V:3.10-32       C:\Users\Developer\AppData\Local\Programs\Python\Python310-32\python.exe

You create environment targets with precise versions by passing flags directly to py:

powershell
# Create an environment pinned to Python 3.11
py -3.11 -m venv .venv311

# Create an environment pinned to Python 3.12
py -3.12 -m venv .venv312

To configure system-wide or user-wide defaults for py.exe, create a py.ini file. This prevents unexpected version jumps when new runtimes are installed.

Place the configuration file at %LOCALAPPDATA%\py.ini:

ini
[defaults]
python=3.12

[commands]
python3=3.12

Save it using PowerShell:

powershell
@"
[defaults]
python=3.12
"@ | Out-File -FilePath "$env:LOCALAPPDATA\py.ini" -Encoding utf8

Verify py respects it:

powershell
py -c "import sys; print(sys.version)"

It should evaluate directly to your configured default minor version.

Shebang Support on Windows

One underused advantage of the Python launcher on Windows is its native shebang processing. Windows does not support hashbangs in the kernel like Linux, but py.exe emulates this exact behavior.

Save a script named process_data.py:

python
#!/usr/bin/env python3.11
import sys

print(f"Executing under interpreter: {sys.executable}")
print(f"Target version: {sys.version_info.major}.{sys.version_info.minor}")

Execute the script through the launcher without specifying any version flag:

powershell
py .\process_data.py

The launcher parses line 1, skips your default Python 3.12, routes execution straight to Python 3.11, and produces:

text
Executing under interpreter: C:\Program Files\Python311\python.exe
Target version: 3.11

If you activate a virtual environment in that shell, py.exe detects the VIRTUAL_ENV environment variable automatically. It diverts execution to the virtual environment interpreter instead of the system interpreter, matching Unix behavior:

powershell
.\.venv312\Scripts\Activate.ps1
py .\process_data.py

Output:

text
Executing under interpreter: C:\Projects\service-core\.venv312\Scripts\python.exe
Target version: 3.12

Edge Case 1: NTFS Mark-of-the-Web Blocking Individual Activation Scripts

If you clone a repository as a .zip archive using a web browser instead of git clone, Windows tags the archive with an alternate data stream named Zone.Identifier. When you unpack that archive, Windows propagates this Mark-of-the-Web (ZoneId=3, Internet) to every extracted file.

Even with ExecutionPolicy set to RemoteSigned, running .venv\Scripts\Activate.ps1 will fail with an authorization error because PowerShell treats files with the Mark-of-the-Web as remote files downloaded directly from the web.

Verify if your script has the identifier:

powershell
Get-Item .\.venv\Scripts\Activate.ps1 -Stream "Zone.Identifier" -ErrorAction SilentlyContinue

If it returns content containing ZoneId=3, strip the identifier from the entire directory recursively:

powershell
Get-ChildItem -Path . -Recurse | Unblock-File

Run .venv\Scripts\Activate.ps1 again. It will execute without error.

Edge Case 2: Virtual Environment Invalidation via Hardcoded Base Paths

When venv creates an environment, it populates pyvenv.cfg in the root of the environment with the key home. This key stores the absolute path to the base runtime directory:

ini
home = C:\Program Files\Python312
include-system-site-packages = false
version = 3.12.2
executable = C:\Program Files\Python312\python.exe
command = C:\Program Files\Python312\python.exe -m venv C:\Projects\service-core\.venv

If Python was updated via a minor patch installer (like 3.12.1 to 3.12.2) and the installer cleared or altered the directory structure, or if you rename any parent directory along your project path, the activation script will fail silently or display:

text
No Python at 'C:\Program Files\Python312\python.exe'

Activating the environment via PowerShell still adjusts your prompt because Activate.ps1 only modifies environment variables like $env:PATH and $env:VIRTUAL_ENV. It does not validate the target executable on load. When you then try to invoke python, it errors out.

To repair this without deleting your whole site-packages directory and reinstalling heavy wheels, rebuild the environment in place using the --upgrade flag pointed at your updated base interpreter:

powershell
py -3.12 -m venv --upgrade .venv

This rewrites pyvenv.cfg and replaces the launcher executables inside .venv\Scripts\ with updated pointers, preserving all previously installed packages inside .venv\Lib\site-packages\.

More in Python