3

I need to process large numbers in a PowerShell FOREACH loop. I receive the following exception:

Cannot convert value "60000000000" to type "System.Int32"

[long]$LargeNumber = 60000000000
 foreach ($i in 1..$LargeNumber) {
  $i 
 }

what am I doing wrong?

2
  • Maybe a for loop would work better? Something like for ($i = 1; $i -le $LargeNumber; $i++) Commented Jul 16, 2019 at 17:48
  • 3
    the range operator uses [int32] and you cannot change that. [sigh ...] Commented Jul 16, 2019 at 17:48

3 Answers 3

4

It appears as though there is a limitation on powershell's range operator (..) that limits the input arguments to Int32. I can't find official documentation, but according to this page:

2 Restrictions and a Caveat There are only two basic restrictions on range use. The first restriction is that the numbers in the range must be between -2,147,483,648 and 2,147,483,647, inclusive; this limit is because PowerShell's range operator changes the values into 32-bit .NET integers, which can only take on these values. The second limit is that an individual range can contain no more than 50,001 items.

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

1 Comment

Thank you so much. That makes sense.
1

This seems to work. But I didn't wait for it to finish. 6 million with measure-command took 29 seconds.

measure-command { for($i = 0; $i -le 6000000; $i++) { $i } }     
Seconds           : 29

Maybe 3 days for 60 billion loops?

$LargeNumber = 60000000000
for($i = 0; $i -le $largenumber; $i++) { $i }

It's probably not practical to create a 60 billion array of 8 byte integers with the range operator (450 gigs?). Watch Powershell's Working Set memory go up to 259.61 megs with 1..6million. I almost crashed my computer with higher amounts. I'm on a mac with ps 6.

get-process pwsh

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00      77.98   3,212.20   39615 …02 pwsh

$a = 1..6000000

get-process pwsh

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00     259.61   3,275.24   39615 …02 pwsh

Comments

0

Just for completion. I tweaked the code like below to make it work.

[long]$LargeNumber = 60000000000
[long]$i = 0 
while (1 -eq 1) { 
 $i 
 if ($i -gt $LargeNumber) {
  break 
 }
 $i++
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.