将 Powershell 变量的值获取到 Python (wxGlade) GUI

Get the value of a Powershell Variables to a Python (wxGlade) GUI

我们这里有一个 powershell 脚本收集一些用户和 windows 信息,将它们存储到 txt.file。

如果我可以选择必须使用 wxGlade GUI 收集哪些信息,那就太好了。

我已经找到了如何执行 powershell 脚本的解决方案。

问题是我如何从 PowerShell 变量接收值到 Python-应用程序:

我们对这样的 Powershell-Infos 感兴趣:

$winver = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\" -Name 
ReleaseID).ReleaseId
$OsName = Get-ComputerInfo OsName
$OsVersion = Get-ComputerInfo OsVersion
$OsBuildNumber = Get-ComputerInfo OsBuildNumber
$OsHardwareAbstractionLayer = Get-ComputerInfo OsHardwareAbstractionLayer
$OfficeVer = reg query "HKEY_CLASSES_ROOT\Word.Application\CurVer"

这是我用于测试目的的 (TKINTER) 代码。 () 我会用一些高级的 wxGlade-Widgets 升级它:

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox as tkmb
from tkinter import simpledialog as tksd
from tkinter import filedialog as tkfd
from pathlib import Path
from datetime import datetime

# First line
root = tk.Tk()
font_size = tk.IntVar(value=12)

# configure root
root.title('Powershell Test')
root.geometry('800x600+300+300')
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.configure(bg='#888')

import subprocess  # IMPORT FOR SUB PROCESS . RUN METHOD

POWERSHELL_PATH = "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe"  # 
POWERSHELL EXE PATH
ps_script_path = 
"C:\Users\mr3968\PycharmProjects\SystemScriptWithGUI\Powershell_Scripts\browser.ps1"  # 
YOUR POWERSHELL FILE PATH

class Utility:  # SHARED CLASS TO USE IN OUR PROJECT

    @staticmethod    # STATIC METHOD DEFINITION
    def openbrowser(script_path, *params):  # SCRIPT PATH = POWERSHELL SCRIPT PATH,  PARAM = 
POWERSHELL SCRIPT PARAMETERS ( IF ANY )

        commandline_options = [POWERSHELL_PATH, '-ExecutionPolicy', 'Unrestricted', 
ps_script_path]  # ADD POWERSHELL EXE AND EXECUTION POLICY TO COMMAND VARIABLE
        for param in params:  # LOOP FOR EACH PARAMETER FROM ARRAY
            commandline_options.append("'" + param + "'")  # APPEND YOUR FOR POWERSHELL SCRIPT

        process_result = subprocess.run(commandline_options, stdout = subprocess.PIPE, stderr 
= subprocess.PIPE, universal_newlines = True)  # CALL PROCESS

        print(process_result.returncode)  # PRINT RETURN CODE OF PROCESS  0 = SUCCESS, NON- 
                                            ZERO = FAIL
        print(process_result.stdout)      # PRINT STANDARD OUTPUT FROM POWERSHELL
        print(process_result.stderr)      # PRINT STANDARD ERROR FROM POWERSHELL ( IF ANY 
                                            OTHERWISE ITS NULL|NONE )

            if process_result.returncode == 0:  # COMPARING RESULT
            Message = "Success !"
        else:
            Message = "Error Occurred !"

        return Message  # RETURN MESSAGE

powershell_frame = ttk.Frame(notebook)
notebook.add(powershell_frame, text='Powershell Test 1', underline=0)
powershell_frame.columnconfigure(2, weight=1)
powershell_frame.rowconfigure(1, weight=1)

# button open the browser
open_browser_btn = ttk.Button(
    powershell_frame,
    text='Open the browser'
)
open_browser_btn.grid(sticky=tk.E, ipadx=5, ipady=5)

open_browser_btn.configure(command=Utility.openbrowser(POWERSHELL_PATH))

root.mainloop()

以这种方式制作是否有意义,或者使用本机 python 代码收集所有这些信息是否更容易?

感谢您的支持。

我.

编辑:我认为这是找到 e 的一个很好的解决方案。 G。办公室版本:

注意:从 Python 调用 PowerShell 方便(实现简洁的解决方案),但 昂贵(子进程创建单独需要时间,而且 Get-ComputerInfo 调用也特别慢)。


最好的方法可能是:

  • 让 PowerShell 构造一个 对象,其属性包含所有感兴趣的值,并且 以JSON格式输出.

  • 解析Python中返回的JSON文本,并根据需要访问解析对象的属性。

这里是您的 PowerShell 脚本 的简化重构。

$cinfo = Get-ComputerInfo
# Construct and output and object whose properties contain all data of interest, 
# in JSON format.
[pscustomobject] @{
  winver = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId
  OsName = $cinfo.OsName
  OsVersion = $cinfo.OsVersion
  OsBuildNumber = $cinfo.OsBuildNumber
  OsHardwareAbstractionLayer = $cinfo.OsHardwareAbstractionLayer
  OfficeVer = Get-ItemPropertyValue "registry::HKEY_CLASSES_ROOT\Word.Application\CurVer" '(default)'
} | ConvertTo-Json

一个简单的PythonJSON解析示例:

import json, subprocess

# Use a simplified sample call to PowerShell.
# In your code, use process_result.stdout
jsonFromPowerShell = subprocess.run(
  ['pwsh', '-noprofile', '-c', '''
    [pscustomobject] @{ winver = 'foo'; osName = 'bar' } | ConvertTo-Json
  '''],
  stdout = subprocess.PIPE
).stdout

# Parse the JSON text into a dictionary.
dict = json.loads(jsonFromPowerShell)

# Enumerate the dictionary entries and print them.
for key in dict:
  print(key + ': ' + dict[key])

输出:

winver: foo
osName: bar

检查第一个 属性 的

检查 this answer 第二个 属性。

我不确定 $OsVerrsion 和 $WinVersion 之间有什么区别。你是 运行 PowerShell,所以你是 运行 Windows.

并且内部版本号在第一个 link 之前可用。

因此 python 中至少有一些选项可以得到...

并且您已经在 Python 中获得了 Office 版本的示例。