我有以下简单的函数,它在脚本中多次使用,该脚本遍历目录并检查其中文件的存在时间。
function log($Message) {
$logFilePath = 'C:\logPath\myLog.txt'
$date = Get-Date -Format 'yyyyMMddHHmmss'
$logMessage = "{0}_{1}" -f $date,$Message
if(Test-Path -Path $logFilePath) {
$logFileContent = Get-Content -Path $logFilePath
} else {
$logFileContent = ''
}
$logMessage,$logFileContent | Out-File -FilePath $logFilePath
}
我发现这会耗尽所有内存。我不明白为什么。我认为一旦函数运行,函数中的变量范围就会被破坏。我通过将 Remove-Variable logMessage,logFileContent,logFilePath,date
添加到函数的末尾来解决 ram 问题,但想知道如何解决这个 ram 问题,以及为什么函数不会自动销毁。
最佳答案
Powershell 或 .Net 有一个垃圾收集器,所以释放内存不是即时的。 Garbage Collection in Powershell to Speed Scripts此外,Powershell 7 中的内存管理可能更好。我尝试多次重复您的功能,但内存使用量没有超过几百兆。
可能有一些更有效的 .net 方法可以在文件前添加一行:Prepend "!" to the beginning of the first line of a file
我有一种奇怪的方式来添加一行。我不确定这对大文件的效果如何。对于 700 兆的文件,工作集内存保持在 76 兆。
$c:file
one
two
three
$c:file = 'pre',$c:file
$c:file
pre
one
two
three
ps powershell
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
607 27 67448 76824 1.14 3652 3 powershell
关于function - 函数中的日志文件变量会占用所有内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61672910/