如何通过python执行powershell命令,并给出与在终端中运行相同的结果?

2024-06-30 15:49:02 发布

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

我的psScript.ps1文件的内容:

powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
powershell -Command "gp HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | select DisplayName, DisplayVersion, Publisher | Format-Table -AutoSize | Out-String -Width 4096 > C:\\temp\\testOut.txt" 

从终端:我会像这样运行,它产生了正确的结果: powershell C:\\Users\\jnguyen19\\scratchPad\\psScript.ps1

终端命令的输出,前几行是:

DisplayName                                                                    DisplayVersion     Publisher                    
-----------                                                                         --------------     ---------                    
Windows Driver Package - Plantronics, Inc. (usbser.ntamd64) Ports  (04/21/2009 5.1) 04/21/2009 5.1     Plantronics, Inc.            
Windows Driver Package - Cambridge Silicon Radio (CSRBC) USB  (10/26/2012 2.4.0.0)  10/26/2012 2.4.0.0 

然而,无论何时,无论我在Python、Popen、Pipe、Subprocess、os.system、Subprocess.run、Subprocess.call、Subcess.check_输出中使用什么,我都会得到完全不同的输出集

python脚本:

import subprocess, sys

f=open("C:\\temp\\textOut.txt", "w")
p = subprocess.Popen(["powershell.exe",
          "C:\\Users\\jnguyen19\\scratchPad\\psGetAppVersions.ps1"],stdout=f).communicate()

python脚本的输出,前几行:

DisplayName                                                                   DisplayVersion   Publisher                                                   
-----------                                                                   --------------   ---------                                                   
Cisco Webex Meetings                                                          40.2.8           Cisco Webex LLC                                             
Carbon Black Sensor                                                           6.2.2.90503      Carbon Black, Inc. 

请帮忙,我花了几天时间在StackOverflow上尝试了半打建议的解决方案,但还没有在Windows10上使用Python3.7.3的解决方案


Tags: txt终端windowsuserstemppublisherincsubprocess