Introduction

On Windows, activating a Python virtual environment in PowerShell often fails with an execution policy error. The Activate.ps1 script is blocked by default because Windows PowerShell restricts running unsigned scripts to protect against malware.

Symptoms

  • Running .\venv\Scripts\Activate.ps1 produces:
  • `
  • .\venv\Scripts\Activate.ps1 : File C:\project\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
  • `
  • Command prompt activation works but PowerShell does not
  • Git Bash may also fail with similar policy restrictions

Common Causes

  • Default PowerShell execution policy set to Restricted
  • Group Policy enforced by IT department preventing policy changes
  • Activating from an unsigned script location
  • Using python -m venv which creates both .bat and .ps1 scripts

Step-by-Step Fix

  1. 1.Check current execution policy:
  2. 2.```powershell
  3. 3.Get-ExecutionPolicy -List

# Output shows: # Scope ExecutionPolicy # MachinePolicy Undefined # UserPolicy Undefined # Process Undefined # CurrentUser Undefined # LocalMachine Restricted ```

  1. 1.Set policy for current user (recommended approach):
  2. 2.```powershell
  3. 3.Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
  4. 4.# Confirm with Y when prompted
  5. 5.`
  6. 6.Bypass policy for single session (if you cannot change policy):
  7. 7.```powershell
  8. 8.powershell -ExecutionPolicy Bypass -Command "& '.\venv\Scripts\Activate.ps1'"
  9. 9.`
  10. 10.Use the batch file instead of PowerShell script:
  11. 11.```cmd
  12. 12.venv\Scripts\activate.bat
  13. 13.`
  14. 14.This works from CMD or from PowerShell when called via:
  15. 15.```powershell
  16. 16.& cmd /c "venv\Scripts\activate.bat"
  17. 17.`
  18. 18.Sign the activation script (enterprise environments):
  19. 19.```powershell
  20. 20.$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
  21. 21.Set-AuthenticodeSignature -FilePath .\venv\Scripts\Activate.ps1 -Certificate $cert
  22. 22.`
  23. 23.Use pyenv-win as alternative:
  24. 24.```powershell
  25. 25.pyenv global 3.12.0
  26. 26.# No activation script needed
  27. 27.`

Prevention

  • Set execution policy during machine setup: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
  • Use python -m venv with the understanding it creates both script types
  • Document the activation method in your project README for Windows users
  • Consider using direnv or pipenv which handle activation automatically
  • For CI/CD pipelines on Windows, use activate.bat which has no policy restrictions