Why is the maximum variables count 4096 in PowerShell 5

Viewed 1185

Just for fun I ran that code:

for ($i = 0; $i -le 9999; ++$i) { New-Variable $i $i -ErrorAction Stop }

PowerShell 5.1 returned:

New-Variable : Cannot create variable 4073 because variable capacity 4096 is exceeded for this scope.

But in PowerShell 7.0.3 I changed for for creating 1 milliard variables.
And I'm tired of waiting.. and canceled it when pwsh ate 7 Gb of my RAM...
$i was 18,401,068 at that moment!

It meant that PS 7.0.3 has no limit for variables count or it is very high.

So why is there limit for 4096 variables count in PS 5.1?

1 Answers

So why is there limit for 4096 variables count in PS 5.1?

Because someone, at some point, thought it was a good idea. That's it.

Maybe someone added it because variable operations in PowerShell are extremely expensive and not super memory efficient. Perhaps one of the developers ran a loop much like yours during testing and it ate up all the memory on his machine and it seemed like an easy stopgap. We may never know.

What we can tell from publicly available information is that the limitation was removed long before the GA release of PowerShell Core 6.0 - exactly because there was no good argument for keeping it.

Related