【发布时间】:2021-04-14 13:54:46
【问题描述】:
所以我的问题是如何在 python 中运行 PowerShell 脚本,使用来自 python 的可传递变量,然后让 python 运行 PowerShell 脚本,然后从那里将 PowerShell 脚本中的特定变量传递给 python 脚本。
我已经拥有的是每个代码单独工作。
如您所见,我正在从 .ini 文件中传递隐藏变量,并从那里尝试将 compList 传递给 Powershell。
我不确定我是否正在运行调用 PowerShell 并在我的 python 脚本中传递参数的命令
preferences = configparser.ConfigParser()
preferences.read('config.ini')
hostName = preferences.get('Directory', 'hostName')
port = preferences.get('Directory', 'port')
serviceName = preferences.get('Directory', 'serviceName')
usr = preferences.get('Credentials', 'userName')
pswrd = preferences.get('Credentials', 'password')
compList = preferences.get('ComputerList', 'compList')
compList = list(compList.split(","))
p = subprocess.Popen(["powershell.exe", r"C:\Users\pecorgx\TestPS1.ps1", 'arg1 @("compList")'], stdout=sys.stdout)
p.communicate()
我的 PowerShell 脚本:
$ArrComputers = $arg1
Clear-Host
foreach ($Computer in $ArrComputers)
{
$computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
$computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer
$computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer
$computerCPU = get-wmiobject Win32_Processor -Computer $Computer
$hdds = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3
write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan
"-------------------------------------------------------"
"Manufacturer: " + $computerSystem.Manufacturer
"Model: " + $computerSystem.Model
"Serial Number: " + $computerBIOS.SerialNumber
"CPU: " + $computerCPU.Name
foreach ($computerhdd in $hdds) { "HDD Drive Letter: " + $computerhdd.DeviceID + "HDD Capacity:" + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB" + " HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) }
"RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
"Operating System: " + $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion
"User logged In: " + $computerSystem.UserName
"Last Reboot: " + $computerOS.ConvertToDateTime($computerOS.LastBootUpTime)
""
"-------------------------------------------------------"
}
我认为我传递正确,但我希望 Powershell 传递回我的 python 脚本
$computerSystem.TotalPhysicalMemory/1GB
$computerSystem.Manufacturer
$computerSystem.Model
$computerBIOS.SerialNumber
$computerCPU.Name
我希望这个 var $computerHDD.Size/1GB 被传递到一个列表中,以便也传递给我的 python 脚本
编辑:我决定只使用.txt 来传递命令。我制作了$myOBJ = "" | Select "computer" 然后制作了$myOBJ.computer = [string](....) 和(...) 是我想在脚本运行后传回的东西
很想知道在没有第三方帮助的情况下使用的解决方案
【问题讨论】:
-
如果你有powershell脚本打印出json,你应该可以很容易地在python中反序列化它
-
“打印输出”是指标准输出,而不是文件。
-
为什么你在这个命令中有这个随机的
r---subprocess.Popen(["powershell.exe", r"C:\Users\pecorgx\TestPS1.ps1"在你的ps1中,你没有在任何地方显示$arg1中的内容,所以$ArrComputers = $arg1会为空。将您所追求的信息设置为 pscustomobject 的哈希表并将其返回会更谨慎。另外,为什么不直接使用内置的Get-ComputerInfocmdlet 来获取此信息而不是所有这些调用? -
r 用于原始字符串
标签: python powershell