gpt4 book ai didi

powershell - 在 Powershell 中将标准输入重定向到大文件 - 内存消耗

转载 作者:行者123 更新时间:2023-12-04 02:11:11 24 4
gpt4 key购买 nike

在 PowerShell 中,将标准输入重定向到文件的常规方法是通过管道传输文件的内容:

Get-Content input-file.txt | Write-Host

但是,如果文件非常大,PowerShell 就会开始消耗大量内存。使用较小的 -ReadCount 似乎可以加快 Get-Content 开始将行输入命令的速度,但内存消耗仍然很大。

为什么内存占用这么高? PowerShell 是否将文件的内容保留在内存中,即使它不需要?有什么方法可以缓解这种情况吗?

最佳答案

以下函数将使用 .NET StreamReader 逐行读取文件类并将每一行发送到管道中。将此发送至 Out-Null在将近 2,000,000 行的日志文件 (~186 MB) 上执行时,我的内存使用量只增加了几十 KB:

function Get-ContentByLine {
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][PsObject]$InputObject
)

begin {
$line = $null
$fs = [System.IO.File]::OpenRead($InputObject)
$reader = New-Object System.IO.StreamReader($fs)
}

process {
$line = $reader.ReadLine()
while ($line -ne $null) {
$line
$line = $reader.ReadLine()
}
}

end {
$reader.Dispose();
$fs.Dispose();
}
}

你会像这样调用它:

PS C:\> Get-ContentByLine "C:\really.big.log" | Out-Null

关于powershell - 在 Powershell 中将标准输入重定向到大文件 - 内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12905924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com