Reputation: 708
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.
Upvotes: 1
Views: 3589
Reputation: 37830
Reference the property not the entire object. So:
$average = ($ComputerCpu[0].LoadPercentage + $ComputerCpu[1].LoadPercentage) / 2
Upvotes: 1
Reputation: 47872
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.
Upvotes: 1