Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PowerShell在返回大字节数组时会消耗GB的RAM?_Powershell - Fatal编程技术网

PowerShell在返回大字节数组时会消耗GB的RAM?

PowerShell在返回大字节数组时会消耗GB的RAM?,powershell,Powershell,我有点难以理解到底发生了什么以及为什么会发生。我有一个小函数,可以获取133MB PNG图像文件的所有字节,将其存储在字节数组中,然后返回。要么是我不理解某些行为,要么是PowerShell中有一个bug $TestFile = 'C:\test.png' function GetByteArray($InputFile) { $ByteArray = [IO.File]::ReadAllBytes($InputFile) Write-Host ( 'Type: ' + $B

我有点难以理解到底发生了什么以及为什么会发生。我有一个小函数,可以获取133MB PNG图像文件的所有字节,将其存储在字节数组中,然后返回。要么是我不理解某些行为,要么是PowerShell中有一个bug

$TestFile = 'C:\test.png'

function GetByteArray($InputFile) {
    $ByteArray = [IO.File]::ReadAllBytes($InputFile)

    Write-Host ( 'Type: ' + $ByteArray.GetType() )
    Write-Host ( 'Size: ' + $ByteArray.Length )

    return $ByteArray
}
$NewArray = GetByteArray -InputFile $TestFile

Write-Host ( 'Type: ' + $NewArray.GetType() )
Write-Host ( 'Size: ' + $NewArray.Length )

pause
我希望函数返回大约133MB大小的
[Byte[]]
,但它没有返回。相反,PowerShell消耗大约5GB的RAM,打印下面的错误消息,并返回一个
[System.Object[]]

Type: byte[] Size: 140151164 Array dimensions exceeded supported range. At F:\test.ps1:10 char:10 + return $ByteArray + ~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], OutOfMemoryException + FullyQualifiedErrorId : System.OutOfMemoryException Type: System.Object[] Size: 134217728 Press Enter to continue...: 类型:字节[] 尺寸:140151164 数组维度超出了支持的范围。 在F:\test.ps1:10 char:10 +返回$ByteArray + ~~~~~~~~~~ +CategoryInfo:OperationsStopped:(:)[],OutOfMemoryException +FullyQualifiedErrorId:System.OutOfMemoryException 类型:System.Object[] 尺寸:134217728 按Enter键继续…: 我不明白什么?为什么字节数组要转换为对象?为什么几乎把我所有的公羊都吃掉了呢?

佩瑟拉尔(一如既往)是正确的,但也许需要更多的解释。从函数返回数组时,PowerShell将展开该数组并将单个元素返回给调用方。在那里,它们被收集到一个常规数组中(
System.Object[]

为了防止出现这种情况,您需要在返回数组结果时将其包装到另一个数组中。PowerShell将只展开外部数组,并将嵌套数组作为单个元素传递给调用方,从而保留类型。可以将其视为应用了一种“传输编码”。使用一元数组构造运算符(
)执行以下操作:

return ,$ByteArray

您返回的不是字节数组,而是单个字节。非常感谢,这确实正确地返回了字节数组!