Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell variable type to hold large numbers

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?

like image 975
RaviLobo Avatar asked Sep 19 '26 00:09

RaviLobo


2 Answers

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.

like image 53
zdan Avatar answered Sep 20 '26 23:09

zdan


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
like image 38
js2010 Avatar answered Sep 21 '26 00:09

js2010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!