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.ps1produces: `- .\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 venvwhich creates both.batand.ps1scripts
Step-by-Step Fix
- 1.Check current execution policy:
- 2.```powershell
- 3.Get-ExecutionPolicy -List
# Output shows: # Scope ExecutionPolicy # MachinePolicy Undefined # UserPolicy Undefined # Process Undefined # CurrentUser Undefined # LocalMachine Restricted ```
- 1.Set policy for current user (recommended approach):
- 2.```powershell
- 3.Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
- 4.# Confirm with Y when prompted
- 5.
` - 6.Bypass policy for single session (if you cannot change policy):
- 7.```powershell
- 8.powershell -ExecutionPolicy Bypass -Command "& '.\venv\Scripts\Activate.ps1'"
- 9.
` - 10.Use the batch file instead of PowerShell script:
- 11.```cmd
- 12.venv\Scripts\activate.bat
- 13.
` - 14.This works from CMD or from PowerShell when called via:
- 15.```powershell
- 16.& cmd /c "venv\Scripts\activate.bat"
- 17.
` - 18.Sign the activation script (enterprise environments):
- 19.```powershell
- 20.$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
- 21.Set-AuthenticodeSignature -FilePath .\venv\Scripts\Activate.ps1 -Certificate $cert
- 22.
` - 23.Use pyenv-win as alternative:
- 24.```powershell
- 25.pyenv global 3.12.0
- 26.# No activation script needed
- 27.
`
Prevention
- Set execution policy during machine setup:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - Use
python -m venvwith the understanding it creates both script types - Document the activation method in your project README for Windows users
- Consider using
direnvorpipenvwhich handle activation automatically - For CI/CD pipelines on Windows, use
activate.batwhich has no policy restrictions