1

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.

1
  • Select-Object -> ForEach-Object Commented Feb 29, 2016 at 18:46

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This works where @EBGreen solution did not (but I don't know why).
1

Reference the property not the entire object. So:

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

2 Comments

For some reason this returns $average as 0
@ATtheincredibleaf possibly the average was zero at the time (or less than 1 and truncated to [int])?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.