简体   繁体   中英

Powershell: Get object value to int array

I'm fairly new to PowerShell

Can someone please explain the most simple way to copy values from an object into a basic integer array without also copying the original object.

Sorry if this is confusing, but what I mean is that I want to capture object values and put them in an integer array where I can then do simple arithmetic on the values

For example

$ComputerCpu = Get-WmiObject win32_processor -computer "MyComputer" | `
    Select-Object {$_.LoadPercentage}

On a Windows Server 2008 VM at work this returns two values

I want to get an average so I tried

$average = ($ComputerCpu[0] + $ComputerCpu[1]) / 2

This cannot work as the values are not of type Int.

I tried casting the values

$average = ([int]$ComputerCpu[0] + [int]$ComputerCpu[1]) / 2

But this results in a cannot convert error.

I know what the problem is but it would be great if someone could explain the fundamental solution to this as I run into this problem a lot and I know there must be a defined solution or a way to avoid this entirely.

Thanks.

PS: If possible please don't provide an alternative solution, as I really want to know how to get an objects values into an integer array so as to perform arithmetic on those values.

Thanks.

In addition to EBGreen's answer, you could use the -ExpandProperty parameter of Select-Object :

$ComputerCpu = Get-WmiObject win32_processor -computer "MyComputer" |
    Select-Object -ExpandProperty LoadPercentage

The rest of your code would work then.

Reference the property not the entire object. So:

$average = ($ComputerCpu[0].LoadPercentage + $ComputerCpu[1].LoadPercentage) / 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM