gpt4 book ai didi

PowerShell内存泄漏误解

转载 作者:行者123 更新时间:2023-12-03 12:36:26 27 4
gpt4 key购买 nike

PowerShell 新手,边做边学。

我创建的进程可以工作,但它最终会锁定我的机器直到完成,耗尽所有内存。我认为我通过强制垃圾收集器解决了这个问题,并且从 for-each 语句转向使用 %() 循环遍历所有内容。

流程快速概要:需要将多个 SharePoint 日志文件合并为单个日志文件,以跟踪所有公司不同 SharePoint 网站的使用情况。 PowerShell 循环遍历 SP 服务器上的所有日志目录,并检查目录中的每个文件是否已存在于我的本地计算机上。如果确实存在,则会附加文件文本,否则会直接复制。对 SharePoint 日志服务器上的每个文件和目录重复进行冲洗。在每个循环之间,我强制执行 GC,因为...因为我的基本理解是循环变量保存在内存中,并且我想刷新它们。我可能看错了。这是有问题的脚本。

$FinFiles = 'F:\Monthly Logging\Logs'

dir -path '\\SP-Log-Server\Log-Directory' | ?{$_.PSISContainer} | %{
$CurrentDir = $_
dir $CurrentDir.FullName | ?(-not $_.PSISContainer} | %{
if($_.Extension -eq ".log"){
$DestinationFile = $FinFiles + '\' + $_.Name
if((Test-Path $DestinationFile) -eq $false){
New-Item -ItemType file -path $DestinationFile -Force
Copy-Item $_.FullName $DestinationFile
}
else{
$A = Get-Content $_.FullName ; Add-Content $DestinationFile $A
Write-Host "Log File"$_.FullName"merged."
}
[GC]::Collect()
}
[GC]::Collect()
}

当然,已完成/附加的日志文件变得非常非常大(最小 300 MB,最大 1GB)。我是不是没有关闭一些我应该关闭的东西,或者在内存中保留一些开放的东西? (目前它占我 8 Gig 内存总量的 7.5。)

提前致谢。

最佳答案

不要像这样嵌套 Get-ChildItem 命令。请改用通配符。尝试:dir "\\SP-Log-Server\Log-Directory\*\*.log"。这应该会改善事情的开始。然后将其移至 ForEach($X in $Y){} 循环,而不是 ForEach-Object{} 循环(您现在使用的循环)。我敢打赌这可以解决您的问题。

所以,我凭空重写了一遍:

$FinFiles = 'F:\Monthly Logging\Logs'

ForEach($LogFile in (dir -path '\\SP-Log-Server\Log-Directory\*\*.log')){
$DestinationFile = $FinFiles + '\' + $LogFile.Name
if((Test-Path $DestinationFile) -eq $false){
New-Item -ItemType file -path $DestinationFile -Force
Copy-Item $LogFile.FullName $DestinationFile
}
else{
$A = Get-Content $LogFile.FullName ; Add-Content $DestinationFile $A
Write-Host "Log File"$LogFile.FullName"merged."
}
}
}

编辑:哦,对了,Alexander Obersht 可能也很正确。您也可能会从 StreamReader 方法中受益。至少您应该使用 Get-Content-readcount 参数,并且没有理由将其保存为变量,只需将其直接通过管道传递给 添加内容 cmdlet。

Get-Content $LogFile.FullName -ReadCount 5000| Add-Content $DestinationFile

为了进一步解释我的答案,如果您在管道中使用 ForEach-Object ,它会将所有内容保留在内存中(无论您的 GC 调用如何)。使用 ForEach 循环不会执行此操作,并且应该可以解决您的问题。

关于PowerShell内存泄漏误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703764/

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