我试图在PowerShell中使用以下命令以字节形式读取1 GB大小的文件:
$data = Get-Content -Encoding byte $filepath
但是它会抛出以下错误: Get-Content : 引发了“System.OutOfMemoryException”类型的异常。
我在网上搜索并发现运行以下命令可以解决此问题,但对我来说没有作用。 set-item wsman:localhost\Shell\MaxMemoryPerShellMB 4096
我试图在PowerShell中使用以下命令以字节形式读取1 GB大小的文件:
$data = Get-Content -Encoding byte $filepath
但是它会抛出以下错误: Get-Content : 引发了“System.OutOfMemoryException”类型的异常。
我在网上搜索并发现运行以下命令可以解决此问题,但对我来说没有作用。 set-item wsman:localhost\Shell\MaxMemoryPerShellMB 4096
默认情况下,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
[io.file]::openread()
将给您一个FileStream
,然后您就可以分阶段地读取它,而不是一次性将其全部加载到内存中。虽然这种方式编程很麻烦,但至少有这个办法。此外,[io.file]::readallbytes()
比get-content
更快,尽管它可能无法解决内存问题。 - Jeroen Mostert