Removing @{} from the output

Viewed 193

The output of the following code is like @{Average = 2}.How can I get the output as Average = 2, Without the @{}.

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

Firstly, I don't think you need to pipe $env:COMPUTERNAME to Foreach-Object, since its of type System.String, not an array or any other type of collection. Would be easier to just use -ComputerName $env:COMPUTERNAME directly. You can see what the type is with ($env:COMPUTERNAME).GetType(). Also have a look at about_environment_variables for more information about Windows environment variables in PowerShell.

Secondly, as @Mathias R. Jessen suggested in the comments, you should use -ExpandProperty to expand the property @{Average = 2} to 2.

Modified command

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

You could also run Get-Help Select-Object -Parameter ExpandProperty to see what ExpandProperty does for Select-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

Also as a side note mentioned in the comments by @mklement0, WMI cmdlets(e.g. Get-WmiObject) have been superseded by CIM cmdlets(e.g. Get-CimInstance) in PowerShell v3 (released in September 2012).. This is also pointed out to you when you run Get-Help Get-WmiObject:

Starting in Windows PowerShell 3.0, this cmdlet has been superseded by Get-CimInstance

And also in this Use CIM cmdlets not WMI cmdlets article. Another reason is that the future is PowerShell Core, which doesn't support WMI cmdlets anymore. You can have a look at this answer for more information.

With all that said, here is the equivalent CIM command using Get-CimInstance.

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

Which will work on both Windows PowerShell and PowerShell Core.

Related