从Python执行PowerShell脚本的最佳方法是什么

2024-04-27 00:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

之前关于这个主题的所有文章都讨论了他们的用例的具体挑战。我认为这将是有用的,有一个帖子只处理最干净的方式运行PowerShell脚本从Python,问是否有人有比我发现的更好的解决方案。

对于绕过PowerShell试图以不同于预期的方式解释命令中的不同控制字符,通常公认的解决方案是使用文件来提供PowerShell命令:

ps = 'powershell.exe -noprofile'
pscommand = 'Invoke-Command -ComputerName serverx -ScriptBlock {cmd.exe \
/c "dir /b C:\}'
psfile = open(pscmdfile.ps1, 'w')
psfile.write(pscommand)
psfile.close()
full_command_string = ps + ' pscmdfile.ps1'
process = subprocess.Popen(full_command_string , shell=True, \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)

当您的python代码需要在每次调用Powershell命令时更改该命令的参数时,您将编写并删除许多供subprocess.Popen运行的临时文件。它工作得很好,但没有必要,也不是很干净。很高兴能够整理一下,并希望得到任何改进的建议,我可以对我找到的解决方案。

不是将包含PS命令的文件写入磁盘,而是使用io模块创建虚拟文件。假设“date”和“server”字符串作为包含此代码的循环或函数的一部分传入,当然不包括导入:

import subprocess
import io
from string import Template
raw_shellcmd = 'powershell.exe -noprofile '

--循环开始,填充服务器和日期变量--

raw_pslistcmd = r'Invoke-Command -ComputerName $server -ScriptBlock ' \
        r'{cmd.exe /c "dir /b C:\folder\$date"}'

pslistcmd_template = Template(raw_pslistcmd)
pslistcmd = pslistcmd_template.substitute(server=server, date=date)
virtualfilepslistcommand = io.BytesIO(pslistcmd)
shellcmd = raw_shellcmd + virtualfilepslistcommand.read()

process = subprocess.Popen(shellcmd, shell=True, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE)

--循环结束--


Tags: 文件命令datestringrawserver解决方案exe