繁体   English   中英

无法让 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 索引 $rndbytes,当 object 创建时,索引类型为int64uint64 如果这不是问题,我很乐意被展示并解释到底出了什么问题。

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

谢谢帮忙~!!

正如评论中提到的,.NET 中的 arrays 长度不能超过 2^31-1 项,因为用于 arrays 的索引值为[int] - 最大值为

这并不是一个真正的问题,因为在 memory中缓冲 20 亿个项目无论如何都是非常低效的 - 如果你想要 10GB 的随机数据,你可以生成并将其以的形式写入磁盘:

# 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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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