简体   繁体   中英

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?

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.

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

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++
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM