无法让 Powershell 分配超过一定大小的数组

Can't Get Powershell to assign an array over a certain size

所以,我正在尝试创建一个 powershell 脚本,该脚本使用各种大小的文件“基准测试”GPG 的速度。给我带来麻烦的具体部分是:

1 $temppath="$($env:Temp)\"
...
4 Measure-Command {$bytes= 10000MB
5 [System.Security.Cryptography.RNGCryptoServiceProvider]$rng = New- Object.System.Security.Cryptography.RNGCryptoServiceProvider
6 $rndbytes = New-Object byte[] $bytes
7 [System.Io.File]::WriteAllBytes("$($temppath)\test.txt", $rndbytes)} | Select-Object -OutVariable gentime | Out-Null; 

$bytes >~ 1.5GB(我使用 10000MB 来测试它)时,我得到一个错误,如果我正确理解发生了什么,对应于字节数组由变量索引的事实输入 int32。具体报错是这样的:

New-Object : Cannot convert argument "0", with value: "10485760000", for "Byte[]" to type "System.Int32": "Cannot convert value "10485760000" to type "System.Int32". Error: "Value was either too large or too small for an Int32.""
At line:6 char:13
+ $rndbytes = New-Object byte[] $bytes
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

有没有办法强制 powershell 在创建对象时使用 int64uint64 类型的索引索引 $rndbytes?如果这不是问题所在,我很乐意展示并解释到底出了什么问题。

请注意,如果您使用,例如 $bytes=1000MB(或写 $bytes=1GB),代码将完美运行。我怀疑我在 $bytes.index > 2^31 -1 左右撞墙了。

感谢帮助~!!

如评论中所述,.NET 中的数组长度不能超过 2^31-1 项,因为用于数组的索引值为 [int] - 其最大值为 2^31- 1.

这不是真正的问题,因为在内存 中缓冲 20 亿项 无论如何效率都非常低 - 如果您想要 10GB 的随机数据,您可以生成并将其写入磁盘 chunks 而不是:

# Set file size
$intendedSize = 10GB

# Create output buffer
$buffer = [byte[]]::new(4KB)

# Create RNG
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()

# Create temp file, open writable filestrem
$tempFile = [System.IO.Path]::GetTempFileName() |Get-Item
$fileStream = $tempFile.OpenWrite()

do {
    # Fill buffer, write to disk, rinse-repeat
    $rng.GetBytes($buffer)
    $fileStream.Write($buffer, 0, $buffer.Length)
} while($fileStream.Length -lt $intendedSize)

# Dispose if filestream + RNG
$fileStream.Dispose()
$rng.Dispose()

4KB 在 Windows 上通常是一个很好的通用缓冲区大小,因为 4KB 是 NTFS 卷上的默认簇大小,大多数现代 CPU 的 L1 缓存大小可被 4KB

整除