Powershell出现Get-Content异常:抛出类型为“System.OutOfMemoryException”的异常。

3

我试图在PowerShell中使用以下命令以字节形式读取1 GB大小的文件:

$data = Get-Content -Encoding byte $filepath

但是它会抛出以下错误: Get-Content : 引发了“System.OutOfMemoryException”类型的异常。

我在网上搜索并发现运行以下命令可以解决此问题,但对我来说没有作用。 set-item wsman:localhost\Shell\MaxMemoryPerShellMB 4096


我正在使用 PowerShell 2.0 版本,无法升级到新版本。 - VarunVyas
1
阅读文件的目的是什么?它是否需要一次性全部驻留在内存中? - mjolinor
2
如果其他方法都失败了,你可以通过PowerShell调用.NET类:[io.file]::openread()将给您一个FileStream,然后您就可以分阶段地读取它,而不是一次性将其全部加载到内存中。虽然这种方式编程很麻烦,但至少有这个办法。此外,[io.file]::readallbytes()get-content更快,尽管它可能无法解决内存问题。 - Jeroen Mostert
1
如果文件可以“分批”处理,并且不需要一次性读入内存,则使用正确的-ReadCount设置的Get-Content可能比[io.file]方法更快且更易于编码。 - mjolinor
我需要读取文件并将字节 blob 提供给基于 REST 的调用,分块读取可以吗? - VarunVyas
显示剩余2条评论
1个回答

1

默认情况下,MaxMemoryPerShellMB = 1024MB。如果您想读取大于1GB的大文件,则需要设置MaxMemoryPerShellMB。

使用以下代码设置MaxMemoryPerShellMB-

    function setpsmem
    {
          $winrmstatus = (get-service WinRM).Status
         if ($winrmstatus -eq 'Running')
    {
        $currentpsmem = (Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB).value
        if ($currentpsmem -le 4096)
        {            
            Set-Item WSMan:\localhost\Plugin\Microsoft.PowerShell\Quotas\MaxMemoryPerShellMB 4096
            Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 4096
            Restart-Service winrm
            $currentmemory = (Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB).value
            Write-Host "Script assign $currentmemory[MB] of memory to PowerShell" -ForegroundColor Green
        } 
        else
        {
            $currentpsmem = (Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB) | Select-Object value
            Write-Host "Powrshell has $currentpsmem[MB] of memory." -ForegroundColor Green
        } 
    }
    else
    {
        Write-Host "WinRM services is not running on current host." -ForegroundColor Red
    }

} setpsmem

尝试一下。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接