bomsabado
bomsabado

Reputation: 45

loop through a collection of range of numbers in one line powershell

I am trying to find a way to loop through a collection of range of numbers in PowerShell. I have tried below and it works

foreach ($i in 1..3)
{
    "$i"
}

foreach ($i in 1,2,3)
{
    "$i"
}

However when I try below, I get a error message

foreach ($i in 1..3,4..8)
{
  "$i"
}

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32". At line:1 char:1

  • $collection1 = 1..3,4..8
  •   + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
      + FullyQualifiedErrorId : ConvertToFinalInvalidCastException
    

Is there a way to loop through a collection of range of numbers in PowerShell.

Upvotes: 1

Views: 2676

Answers (1)

vonPryz
vonPryz

Reputation: 24091

The reason for the error is that

foreach ($i in 1..3,4..8)

will pass to the foreach enumerator an array of two elements. The first element is an array that contains values 1,2,3 and the second is also an array that contains values 4-8. However, foreach expects to find values from a collection, not other collections (arrays in this case).

To get one array for foreach, create two arrays and add those together. Like so,

$a1 = 1..3
$a2 = 4..8
$k = $a1+$a2

foreach($i in $k) {$i}           
1
2
3
4
5
6
7
8

Or, wrap the ranges in parenthesis so the result is converted to a single array:

foreach($i in (1..3),(4..8)) {$i}
1
2
3
4
5
6
7
8

Upvotes: 3

Related Questions