2

I'm trying to execute a ps1 file in my python script.

proc = subprocess.Popen(["powershell.exe", 'F:/FOLDER/FOLDER OK/myfile.ps1'])

It stopped at F:/FOLDER/FOLDER so I added additional quotes like this:

proc = subprocess.Popen(["powershell.exe", '"F:/FOLDER/FOLDER OK/myfile.ps1"'])

No error now, but it didn't execute the script either... Any idea?

Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55
  • Possible duplicate of [How to run a powershell script with white spaces in path from command line?](https://stackoverflow.com/questions/45760457/how-to-run-a-powershell-script-with-white-spaces-in-path-from-command-line) – bgfvdu3w Mar 05 '18 at 12:55
  • windows sucks so much sometimes. Have you tried the following workaround: `proc = subprocess.Popen(["powershell.exe", 'myfile.ps1'],cwd='F:/FOLDER/FOLDER OK')` ? – Jean-François Fabre Mar 05 '18 at 12:59
  • 1
    @Mark - definitely relevant, but not a duplicate. – Jeff Zeitlin Mar 05 '18 at 12:59
  • @Jean-FrançoisFabre didn't work :/ no error nothing, it just didn't execute the file – Baptiste Arnaud Mar 05 '18 at 13:03
  • 2
    @JeffZeitlin Answer is there. Use `-File` and it will work. This isn't a Python-specific issue or anything from what it seems. – bgfvdu3w Mar 05 '18 at 13:03
  • @Mark - agreed that the relevant information is there, and that the querent should be able to derive my answer below from it, but the next person might not; that's why I say 'relevant, but not duplicate'. – Jeff Zeitlin Mar 05 '18 at 13:06

1 Answers1

3

powershell.exe does not assume that a parameter is automatically a file to execute; you need to identify all parameters. Use the -File switch

proc = subprocess.Popen(["powershell.exe", "-File", r"F:\FOLDER\FOLDER OK\myfile.ps1"])

The r in r"..." (for raw) turns off escape-sequence processing so that \ can be used without escaping.

See PowerShell Command Line Help at Microsoft Docs.

PowerShell[.exe]
       [-Command { - | <script-block> [-args <arg-array>]
                     | <string> [<CommandParameters>] } ]
       [-EncodedCommand <Base64EncodedCommand>]
       [-ExecutionPolicy <ExecutionPolicy>]
       [-File <FilePath> [<Args>]]
       [-InputFormat {Text | XML}] 
       [-Mta]
       [-NoExit]
       [-NoLogo]
       [-NonInteractive] 
       [-NoProfile] 
       [-OutputFormat {Text | XML}] 
       [-PSConsoleFile <FilePath> | -Version <PowerShell version>]
       [-Sta]
       [-WindowStyle <style>]
mklement0
  • 382,024
  • 64
  • 607
  • 775
Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33
  • As an aside: PowerShell _Core_ now _defaults_ to `-File`, (thought it never hurts to be explicit; the change was necessary to support Unix shebang lines). – mklement0 Mar 05 '18 at 15:40