在Python脚本中运行PowerShell cmdlet

问题描述 投票:1回答:3

我有一个Python脚本,我想运行PowerShell cmdlet。我已经在线查看了,我唯一能找到的就是运行PowerShell脚本,但我觉得要在脚本中编写一个cmdlet,然后点源它来执行会比需要花费更长的时间。

我尝试过以下方式使用subprocess.Popen:

cmd = subprocess.Popen(['C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe', ps_cmdlet])

但是ps_cmdlet是一个python字符串变量,其中包含powershell cmdlet。所以,我显然得到一个“没有这样的文件或目录”错误。有没有办法在python脚本中运行powershell cmdlet而不使用像IronPython这样的东西?

谢谢!

python powershell powershell-v2.0
3个回答
0
投票

尝试以下(ps_cmdlet是一个python字符串):

subprocess.call(ps_cmdlet)

编辑:这是一个将机器的ip配置输出到Powershell的示例:

ps_cmdlet = 'ipconfig'
subprocess.call(ps_cmdlet)

另一个编辑:另一种对我有用的方法是:

ps_cmdlet = 'whatever command you would enter in powershell'
p = subprocess.Popen(ps_cmdlet,stdout=subprocess.PIPE)
p.communicate()

0
投票

这很有效

import subprocess
pl = subprocess.Popen(['powershell', 'get-process'], stdout=subprocess.PIPE).communicate()[0]
print(pl.decode('utf-8'))

-1
投票
import subprocess
process = subprocess.Popen([r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", "get-process"],
                           shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process_output = process.read().splitlines()

上面的脚本将有助于从Python执行PS Cmdlet。

© www.soinside.com 2019 - 2024. All rights reserved.