Home HowTo Operators Splitting Splitting Numbers (and summing them up)
 

Splitting Numbers (and summing them up)

You probably know the operator -split. It can split strings into pieces and uses a regular expression to determine where to split:

PS> 'List,is,comma,separated' –split ','
List
is
comma
separated

PS> 

  Operator -split can split texts easily

Splitting Numbers

But did you know that split can also split numbers into digits? Try this:

PS> 4362 –split ''

4
3
6
2

PS> 

  Operator -split autoconverts numbers to strings

The trick here really is to use an empty expression as split parameter. This way, the operator splits the text after each character.

Summing Up Numbers

Once you have individual numbers, you may want to sum them up. You could do this in a loop, but there is also a cmdlet that is designed for this type of job: Measure-Object!

PS> 4362 –split '' | Measure–Object –sum

Count    : 6
Average  :
Sum      : 15
Maximum  :
Minimum  :
Property :

PS> 4362 –split '' | Measure–Object –sum | Select–Object –ExpandProperty Sum
15

  Measure-Object sums up multiple numbers

Measure-Object autoconverts the strings back to numbers and sums them up. Likewise, when you look at the parameters Measure-Object provides, you could as easily calculate the average, minimum, or maximum value.