Home > Software design >  Get the value of a Powershell Variables to a Python (wxGlade) GUI
Get the value of a Powershell Variables to a Python (wxGlade) GUI

Time:12-14

we have here a powershell script collenting some user and windows infos storing them to a txt.file.

It would be nice if I could choose which information has to be collected with a wxGlade GUI.

I have already a solution how to execute powershell scripts.

The question is how I receive the values from the PowerShell Variables to the Python-Application:

We are interested in such 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"

This is the (TKINTER) Code I use for testing purposes. (Running PowerShell Script from Python) I will upgrade it with some advanced 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()

Does it make sense to make it on this way or is it easier to collect all these infos with a native python code?

Thank you for your support.

I.

EDIT: I think this is a good solution to find e. g. Office Version: Description

CodePudding user response:

Note: Calling PowerShell from Python is convenient (enables concise solutions), but expensive (the child process creation alone takes time, and the Get-ComputerInfo call, in particular, is slow too).


The best approach is probably:

  • Let PowerShell construct an object whose properties contain all the values of interest, and output it in JSON format.

  • Parse the returned JSON text in Python and access the parsed object's properties as needed.

Here's a streamlined reformulation of your PowerShell script.

$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

A simple Python JSON parsing example:

import json, subprocess

# Use a simplified sample call to PowerShell.
# In your code, use process_result.stdout
jsonFromPowerShell = subprocess.run([ 'powershell.exe', '-noprofile', '-c', '''
  [pscustomobject] @{ winver = 'foo'; osName = 'bar' } | ConvertTo-Json
'''], stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True).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])

Output:

winver: foo
osName: bar

CodePudding user response:

Check this answer for the first property.

Check this answer for the second property.

I am not sure what is the difference between $OsVerrsion and $WinVersion. You are running the PowerShell, so you are running Windows.

And the build number is available thru the firt link.

So at least some options are available in python to get...

And you already have the example of getting the Office Version in Python.

  • Related