执行一个powershell文件,其中包含空格的绝对路径

时间:2018-03-05 12:52:11

标签: python powershell subprocess

我试图在我的python脚本中执行ps1文件。

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

它停在F:/FOLDER/FOLDER所以我添加了这样的其他引号:

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

现在没有错误,但它没有执行脚本...... 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

powershell.exe不假定参数自动成为要执行的文件;你需要识别所有参数。使用-File开关

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

r中的r"..."(对于 raw )会关闭转义序列处理,以便可以在不转义的情况下使用\

请参阅Microsoft Docs上的PowerShell Command Line Help

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>]
相关问题