Python调用PowerShell Get-Service命令报错的原因及解决方法
我有一条带多参数的PowerShell命令,在PowerShell里能正常运行,但用Python的subprocess调用时始终报错,试了各种单引号、双引号、三重引号组合都没用。
当前使用的Python代码:
subprocess.run("""powershell.exe Get-Service -Name 'Remote Desktop Services' ""Remote Desktop Configuration"", 'Remote Desktop Services UserMode Port Redirector'""", shell=True, text=True)
PowerShell中可正常运行的命令:
Get-Service -Name "Remote Desktop Services", "Remote Desktop Configuration", "Remote Desktop Services UserMode Port Redirector"
执行Python代码后得到的错误输出:
Get-Service : A positional parameter cannot be found that accepts argument 'Desktop'.
At line:1 char:1
- Get-Service -Name 'Remote Desktop Services', Remote Desktop Configura +
CategoryInfo : InvalidArgument: (:) [Get-Service], ParameterBindingException
FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetServiceCommand
问题出在命令行参数的转义解析上,当通过shell=True调用PowerShell时,参数传递规则和直接在PowerShell内运行不同,带空格的服务名容易被错误拆分。推荐两种解决方式:
方式1:不使用shell=True(更安全推荐)
将命令拆分为参数列表传递,让subprocess自动处理参数转义,避免嵌套引号的混乱:
import subprocess subprocess.run( [ "powershell.exe", "-Command", "Get-Service -Name 'Remote Desktop Services', 'Remote Desktop Configuration', 'Remote Desktop Services UserMode Port Redirector'" ], text=True )
或者进一步拆分每个命令参数,解析逻辑更清晰:
import subprocess subprocess.run( [ "powershell.exe", "-Command", "Get-Service", "-Name", "Remote Desktop Services", "Remote Desktop Configuration", "Remote Desktop Services UserMode Port Redirector" ], text=True )
方式2:正确转义参数(使用shell=True时)
如果必须保留shell=True,需要明确用-Command指定执行内容,通过双引号包裹整个PowerShell命令,内部服务名用单引号隔离,确保参数不被错误拆分:
import subprocess subprocess.run( '''powershell.exe -Command "Get-Service -Name 'Remote Desktop Services', 'Remote Desktop Configuration', 'Remote Desktop Services UserMode Port Redirector'"''', shell=True, text=True )
内容的提问来源于stack exchange,提问作者Cezar

