Search code examples
powershelllogfileget-wmiobjectselect-object

How do I write the value of a single property of a object?


This is how my current script looks like:

$cpu = Get-WmiObject win32_processor | select LoadPercentage
logwrite $cpu #this fuction writes $cpu into a .txt file

The output of the file is:

@{LoadPercentage=4}

I want it to be only the number so that I can make calculations.


Solution

  • That is a pretty simple fix. Instead of selecting the LoadPercentage when running Get-WmiObject, just select the property when calling your function. This will write only the number to your log file.

    $cpulogpath = "C:\Monitoring\$date.csv"
    function logwrite
    {
        param ([string]$logstring)
        add-content $cpulogpath -value $logstring
    }
    
    $cpu = Get-WmiObject win32_processor #don't select the property here
    logwrite $cpu.LoadPercentage #select it here