6

I have a python script which I can run via PowerShell using the following code:

cd User\PythonScripts
python TestFile.py

Now I want to run these simple commands via a PowerShell script (notepad file and saving it as a ps1 file).

I have googled a lot but I cannot find an answer, but I think it should be something like this:

$path = 'C:\User\PythonScripts'
$file = 'TestFile.py

I think I still miss the reference to python (so it knows which program he needs). How do I need to do this?

JosefZ
  • 28,460
  • 5
  • 44
  • 83
Oamriotn
  • 257
  • 1
  • 3
  • 8
  • Welcome to Stack Overflow. Please take the 2-minute [tour]. Moreover, open [Help] and read at least [ask]. Then, [edit] your question to provide more details in your [mcve]. As currently written, it's a bit unclear what do you asking for. Maybe reading `powershell -?` could help. – JosefZ Jan 24 '19 at 16:27

4 Answers4

7

Assuming that python is already in your path variables you can just call a python script like this:

python C:\User\PythonScripts\TestFile.py
Tom Dee
  • 2,516
  • 4
  • 17
  • 25
  • Great, just a simple line of code but it works! Now I only need to hit Run with powershelll. Thanks – Oamriotn Jan 24 '19 at 19:40
  • Placing python in path is no longer optimal. Consider py launcher instead. More info https://stackoverflow.com/a/75139069/10141885. – halt9k Mar 02 '23 at 10:22
5

I think the question is you want to run the python script using powershell .

I think below code will do for you

$path = 'C:\User\PythonScripts'
$file = 'TestFile.py'

$cmd = $path+"\\"+$file  # This line of code will create the concatenate the path and file
Start-Process $cmd  # This line will execute the cmd 

Save the above code as .ps1 and run the that powershell file

Sreevathsabr
  • 649
  • 7
  • 23
1

I have been facing the same problem with Windows10 PowerShell and I have solved it like this:

Go to PowerShell and instead of running the command like this:

PS C:\Windows\system32> python ex1.py

run it as below:

PS C:\Windows\system32> python C:\Users\PCWIZARD\Desktop\hardway\ex1.py

In other words specify the entire path of your ex1.py depending on where you saved your file on your computer. This will print out your code.

Vlad
  • 8,225
  • 5
  • 33
  • 45
0

I think below code will work.

cd C:\User\PythonScripts

.\python TestFile.py

Mention python.exe if it is a executable in place of python. Save above code in .ps1 file and run it on powershell

Ankush
  • 1
  • 1