Why won't Python scripts run properly in PowerShell?

I’m trying to learn Python using the guide “Learn Python the Hard Way” by Zed A. Shaw, but I’m encountering an issue when running Python scripts in PowerShell. I can run scripts, but only when I use .\ in front of the file name, which briefly opens CMD and then closes.

When I attempt to run the file without .\, I get an error saying that the file is not an operable program or script.

I’ve come across several similar questions on Stack Overflow, but none of the solutions have worked for me. Here’s what I’ve tried so far:

  1. I added Python to the environment variable with this command: [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  2. I also modified the $env:PATH by running $env:PATH =$env:PATH+";."

When I check the environment variable PATH, it looks correct, so what else could be causing this issue when trying to run Python in PowerShell Python?

Hey @sakshikuchroo

Hope you’re doing well and making great strides with your setup!

To begin, it’s important to ensure that Python is added to the PATH system-wide. The $env:PATH modification you made might only apply to the current PowerShell session. To make Python available globally, navigate to your system’s environment variable settings and add the Python directory (like C:\Python27) to the system PATH variable. Don’t forget to restart PowerShell after making this change, and then try running Python again—this time without the need for .\.

Hi there! Wishing you smooth sailing on your Python journey.

@joe-elmoufak’s advice is spot on, but if adding Python to PATH doesn’t immediately resolve the issue, here’s another quick check: try using the full path to Python in PowerShell. For instance: C:\Python27\python.exe script.py

This ensures you’re pointing to the exact Python interpreter. Once this works, you can refine your setup to make sure Python is configured correctly in your environment so you don’t need the full path every time.

Hey! Hope everything’s going great and you’re closer to resolving the issue.

Building on what Toby shared, if you’ve confirmed the path works but still face issues running scripts, PowerShell’s execution policy could be the blocker. Run this command to check:

Get-ExecutionPolicy If it shows Restricted, that’s likely why your scripts won’t run. Update it with: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

This will let you run local scripts while maintaining some security. After this tweak, try running your Python script again—it should work smoothly now!