如何写入对象的单个属性的值?

发布于 01-15 08:40 字数 253 浏览 5 评论 0 原文

这就是我当前脚本的样子:

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

文件的输出是:

@{LoadPercentage=4}

我希望它只是数字,以便我可以进行计算。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

失而复得 2025-01-22 08:40:44

qbanet359 的有用答案使用直接属性访问 (. LoadPercentage)在结果对象上,这是这种情况下最简单、最有效的解决方案。

在 PowerShell v3+ 中,这甚至可以通过名为 对象集合(数组、列表)中提取属性值 “https://stackoverflow.com/a/44620191/45375">成员访问枚举

例如,((Get-Date), (Get-Date).AddYears(-1)).Year 返回 20192018 在 2019 年运行时,它们是数组中每个 [datetime] 实例的 .Year 属性值。


如果您确实想要使用Select-Object(或其内置别名,select),例如在处理大型 输入集合逐项,以便利用潜在的内存友好处理:

使用Select-Object< /code> 要提取单个属性,您必须使用-ExpandProperty

Get-WmiObject win32_processor | Select-Object -ExpandProperty LoadPercentage

正如 zett42 注释,使用 =“nofollow”="" noreferrer"="">ForEach-Object 与 "="">简化语法是另一种选择,当使用内置 % 别名时,它可以提供一个简洁的解决方案,方便交互式使用:

# Short for: ForEach-Object -MemberName LoadPercentage
# which in turn is equivalent to: ForEach-Object { $_.LoadPercentage }
Get-WmiObject win32_processor | % LoadPercentage
  • 作为一个除了性能之外(在大多数情况下可能并不重要):令人惊讶的是,
    ForEach-Object -MemberName LoadPercentage
    ForEach-Object { $_.LoadPercentage },至少 PowerShell 7.3.4(撰写本文时的当前版本);请参阅 GitHub 问题 #7700

背景信息:

Select-Object< /code> 默认情况下创建自定义对象[pscustomobject] 实例[1]
),具有您通过 -Property 参数指定的属性(可选隐式,作为第一个位置参数)。

即使指定单个属性[2],这也适用,以便选择LoadPercentage(缩写:Select-Object -Property LoadPercentage )创建类似于以下对象的内容:

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

因为您使用 Add-Content 写入日志文件,所以它是该对象的 .ToString() 字符串表示形式像您一样编写的自定义对象获取是否在可扩展字符串中使用该对象(尝试 "$([pscustomobject] @{ LoadPercentage = 4 })")。

相比之下,参数-ExpandProperty只能应用于单个属性,不会创建自定义对象,而是返回输入对象中该属性的>值

  • 注意:如果该属性的值恰好是一个数组(集合),则其元素将单独输出;也就是说,每个输入对象都会获得多个输出。

[1] 严格来说,它们是 [System.Management.Automation.PSCustomObject] 实例,而类型加速器 [pscustomobject] 令人困惑的是,它们指的是类型 < code>[System.Management.Automation.PSObject],由于历史原因;请参阅此 GitHub 问题

[2] 有一个 < a href="https://github.com/PowerShell/PowerShell/issues/5237" rel="nofollow noreferrer">GitHub 上备受争议的更改请求 Select-Object 仅具有单个属性的默认行为;虽然讨论很有趣,但当前的行为不太可能改变。

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+ this even works with extracting property values from a collection (array, list) of objects, via a feature called member-access enumeration.

E.g., ((Get-Date), (Get-Date).AddYears(-1)).Year returns 2019 and 2018 when run in 2019, which are the .Year property values from each [datetime] instance in the array.


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, so as to take advantage of potentially memory-friendly streaming processing:

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

Get-WmiObject win32_processor | Select-Object -ExpandProperty LoadPercentage

As zett42 notes, using ForEach-Object with simplified syntax is another option, which, when using the built-in % alias makes for a concise solution that is handy for interactive use:

# Short for: ForEach-Object -MemberName LoadPercentage
# which in turn is equivalent to: ForEach-Object { $_.LoadPercentage }
Get-WmiObject win32_processor | % LoadPercentage
  • As an aside re performance (probably won't matter in most cases): Surprisingly,
    ForEach-Object -MemberName LoadPercentage is slower than
    ForEach-Object { $_.LoadPercentage }, up to at least PowerShell 7.3.4 (the current version as of this writing); see GitHub issue #7700.

Background information:

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 positional argument).

This applies even when specifying a single property[2], 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.

  • Note: If the value of that property happens to be an array (collection), its elements are output individually; that is, you'll get multiple outputs per 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.

[2] There's a hotly debated request on GitHub to change Select-Object's default behavior with only a single property; while the discussion is interesting, the current behavior is unlikely to change.

心碎的声音 2025-01-22 08:40:44

这是一个非常简单的修复。无需在运行 Get-WmiObject 时选择 LoadPercentage,只需在调用函数时选择该属性即可。这只会将数字写入您的日志文件。

$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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文