pythonpowershellcmdsubprocess

Run `ps1` scripts without specifying the executor


In Python, we can use subprocess to run bat (cmd) scripts natively, like

import subprocess as sp
sp.run(["D:/Temp/hello.bat"])

works fine. However, it cannot run ps1 scripts natively, codes like

import subprocess as sp
sp.run(["D:/Temp/hello.ps1"])

will cause `WinError 193: %1 is not a valid Win32 application" to be raised.

I thought it was because the .PS1 had not been showing up in PATHEXT and added it there, but it failed again. I also tried the way provided in this answer which seems to be setting the file execution policy and it still wouldn't work.

I know it would work when I add the executor in the call like sp.run(["pwsh", "D:/Temp/hello.ps1"]) or use a bat script as intermediate, but that's not desired. I am using a program which is badly ported from *nix to Windows and it just call whatever I provided as a single executable (on *nix we can use shebang, but not on windows).


Solution