I am trying to pull a variety of system metrics from a PowerShell Script into Python for further processing. I have picked the data that I need and used echo to place it into a txt file which I am attempting to read with Python, but when I look at the Python data, I just get gibberish. Does Powershell use some strange encoding when it outputs to txt files? If so, is there a way to either get PowerShell to output in a format Python can read or instruct Python to read the format PowerShell uses?
The PowerShell Code looks like this:
$Make = Get-CimInstance CIM_ComputerSystem | Select Manufacturer
echo $Make.manufacturer > c:\Mike\Output\SysConfig.txt
$Model = Get-CimInstance CIM_ComputerSystem | Select Model
echo $Model.model >> c:\Mike\Output\SysConfig.txt
$Os = Get-CimInstance Win32_OperatingSystem | Select-Object Caption
echo $Os.caption >> c:\Mike\Output\SysConfig.txt
$CPU = Get-WmiObject Win32_Processor | Select *
echo $CPU.Name >> c:\Mike\Output\SysConfig.txt
echo $CPU.NumberOfCores >> c:\Mike\Output\SysConfig.txt
echo $CPU.NumberOfLogicalProcessors >> c:\Mike\Output\SysConfig.txt
echo $CPU.ThreadCount >> c:\Mike\Output\SysConfig.txt
echo $CPU.MaxClockSpeed >> c:\Mike\Output\SysConfig.txt
echo $CPU.CurrentClockSpeed >> c:\Mike\Output\SysConfig.txt
The text output looks like this:
Hewlett-Packard
HP EliteBook 2570p
Microsoft Windows 10 Pro
Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
2
4
4
2901
2901
And the Python Code looks like this:
with open('c:\mike\output\SysConfig.txt', mode='r') as f:
Manufacturer = f.readlines(1)
Make = f.readlines(2)
OS = f.readlines(3)
CPU_Name = f.readlines(4)
CPU_Phys_Cores = f.readlines(5)
CPU_Log_Cores = f.readlines(6)
CPU_Threads = f.readlines(7)
CPU_Max_Clock = f.readlines(8)
CPU_Curr_Clock = f.readlines(9)
print(Manufacturer)
print(Make)
print(OS)
print(CPU_Name)
print(CPU_Phys_Cores)
print(CPU_Log_Cores)
print(CPU_Threads)
print(CPU_Max_Clock)
print(CPU_Curr_Clock)
| Out-File -FilePath C:\Mike\Output\SysConfig.txt -Encoding UTF8 -Append, not a redirect operator>>. Also, what's the point of using Python when you're already using PowerShell?readlines()incorrectly. The argument tells it the maximum number of lines to read, it's not the index of a line in file. I suggest you usereadline()instead and just putf.readline()everywhere.