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

笑着哭i 提交于 2019-11-26 05:30:03

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

qbanet359's helpful answer uses direct property access (.LoadPercentage) on the result object, which is the simplest and most efficient solution in this case.

In PowerShell v3 or higher this even works with extracting property values from a collection of objects, via a feature called member enumeration.


In cases where you do want to use Select-Object (or its built-in alias, select), such as when processing a large input collection item by item:

To use Select-Object to extract a single property value, you must use -ExpandProperty:

Get-WmiObject win32_processor | Select-Object -ExpandProperty LoadPercentage

Background:

Select-Object by default creates custom objects ([pscustomobject] instances[1] ) that have the properties you specify via the -Property parameter (optionally implicitly, as the 1st argument).

This applies even when specifying a single property, so that select LoadPercentage (short for: Select-Object -Property LoadPercentage) creates something like the following object:

$obj = [pscustomobject] @{ LoadPercentage = 4 } # $obj.LoadPercentage yields 4

Because you use Add-Content to write to your log file, it is the .ToString() string representation of that custom object that is written, as you would get if you used the object in an expandable string (try "$([pscustomobject] @{ LoadPercentage = 4 })").

By contrast, parameter -ExpandProperty, which can be applied to a single property only, does not create a custom object and instead returns the value of that property from the input object.


[1] Strictly speaking, they're [System.Management.Automation.PSCustomObject] instances, whereas type accelerator [pscustomobject], confusingly, refers to type [System.Management.Automation.PSObject], for historical reasons; see this GitHub issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!