【问题标题】:Removing @{} from the output [duplicate]从输出中删除 @{} [重复]
【发布时间】:2020-03-24 23:53:22
【问题描述】:

以下代码的输出类似于@{Average = 2}。如果没有@{},我怎样才能得到Average = 2 的输出。

$cpu = $ENV:COMPUTERNAME |Foreach-Object {
    Get-WmiObject -computername $_ win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
}

【问题讨论】:

  • Select Average -> Select -Expand Average
  • @MathiasR.Jessen - 建议将其作为答案,而不是在 cmets 中回答问题。
  • 我想要这台机器的cpu使用率。 $ENV:COMPUTERNAME 将给出主机的名称并找到主机的 CPU 平均使用率,我将其通过管道传输到 Foreach-Object。 @Ro
  • 顺便说一句:CIM cmdlet(例如,Get-CimInstance)在 PowerShell v3(2012 年 9 月发布)中取代了 WMI cmdlet(例如,Get-WmiObject)。因此,应该避免使用 WMI cmdlet,尤其是因为 PowerShell Core,所有未来的努力都将用于,甚至不再拥有它们。有关详细信息,请参阅this answer
  • | % average。请注意,他必须为 get-ciminstance 启用 wsman 而不是 dcom。

标签: powershell


【解决方案1】:

首先,我认为您不需要将$env:COMPUTERNAME 传递给Foreach-Object,因为它的类型为System.String,而不是数组或任何其他类型的集合。直接使用-ComputerName $env:COMPUTERNAME 会更容易。您可以使用($env:COMPUTERNAME).GetType() 查看类型。另请查看about_environment_variables,了解有关 PowerShell 中的 Windows 环境变量的更多信息。

其次,正如 cmets 中建议的@Mathias R. Jessen,您应该使用-ExpandProperty 将属性@{Average = 2} 扩展为2

修改后的命令

Get-WmiObject -ComputerName $env:COMPUTERNAME -Class Win32_Processor `
    | Measure-Object -Property LoadPercentage -Average `
    | Select-Object -ExpandProperty Average

您也可以运行Get-Help Select-Object -Parameter ExpandProperty 来查看ExpandPropertySelect-Object 的作用。

-ExpandProperty <String>
    Specifies a property to select, and indicates that an attempt should be made to expand that property. Wildcards are permitted in the property name.

    For example, if the specified property is an array, each value of the array is included in the output. If the property contains an object, the properties of that object are displayed in the output.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       False
    Accept wildcard characters?  false

另外作为 @mklement0 在 cmets 中提到的旁注,WMI cmdlet(例如 Get-WmiObject)已被 PowerShell v3(2012 年 9 月发布)中的 CIM cmdlet(例如 Get-CimInstance)取代。这是在你运行Get-Help Get-WmiObject时也向你指出:

从 Windows PowerShell 3.0 开始,此 cmdlet 已被 Get-CimInstance 取代

在这篇Use CIM cmdlets not WMI cmdlets 文章中也是如此。另一个原因是未来是 PowerShell Core,它不再支持 WMI cmdlet。您可以查看answer 了解更多信息。

说了这么多,下面是使用Get-CimInstance 的等效CIM 命令。

Get-CimInstance -ClassName Win32_Processor `
    | Measure-Object -Property LoadPercentage -Average `
    | Select-Object -ExpandProperty Average

这适用于 Windows PowerShellPowerShell Core

【讨论】:

    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2021-05-04
    • 2015-09-26
    • 2019-02-18
    • 2023-03-15
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多