【问题标题】:Powershell gives Get-Content : Exception of type 'System.OutOfMemoryException' was thrownPowershell 提供 Get-Content:引发了“System.OutOfMemoryException”类型的异常
【发布时间】:2015-02-13 16:07:48
【问题描述】:

我正在尝试使用以下命令在 powershell 中以字节形式读取大小为 1 GB 的文件,

$data = Get-Content -Encoding 字节 $filepath

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

搜索网络并发现在命令下运行可以修复它,但这对我不起作用。 设置项 wsman:localhost\Shell\MaxMemoryPerShellMB 4096

【问题讨论】:

  • 我使用的是powershell 2.0版本,无法迁移到新版本
  • 读取文件的目的是什么?这一切都需要一次驻留在内存中吗?
  • 如果所有其他方法都失败了,您始终可以从 PowerShell 调用 .NET 类:[io.file]::openread() 会给您一个 FileStream,然后您可以零碎地阅读它,而不是试图一次将其全部放入内存.编程很尴尬,但它是一些东西。此外,[io.file]::readallbytes()get-content 更快,尽管它可能对内存问题没有帮助。
  • 您需要以管理员身份运行Set-Item 命令才能使其工作。但请注意在 PowerShell 中处理大量文件。事情可能会变得……相当缓慢。
  • 如果文件可以“零碎”地处理,并且不需要一次全部读入内存,则使用正确的 -ReadCount 设置的 Get-Content 可以比 [ io.file] 方法。

标签: powershell out-of-memory


【解决方案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

试试看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2013-08-28
    • 2015-07-18
    • 2011-02-14
    相关资源
    最近更新 更多