在Windows 2012 R2版本上运行的服务器上
PS C:\Users\admin> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
我需要删除包含许多子文件夹的文件夹中超过180天的文件。这很简单,但是不是,当有成千上万个文件并且该文件夹大约为800GB时。使用Get-ChildItem,它首先在检查日期的同时递归读取所有文件,然后开始删除它们……好吧,这要花很多时间,并且服务器最终会耗尽内存。
所以-任何想帮助我加快我的代码速度的人都可以这样(删除部分)
...
...
foreach ($i in Get-ChildItem $TargetFolder -recurse -exclude
$skipFilePatterns | where { ! $i.PSIsContainer }) {
if (! $i.PSIsContainer -and $i.LastWriteTime -lt ($(Get-Date).AddDays(-$keepForDays))) {
# Add -WhatIf to test the script, remove it when confirmed
$timeStamp = $i.LastWriteTime
$fullName = $i.FullName
$log.Info("Deleting: $fullName with timestamp (LastWriteTime): $timeStamp")
Remove-Item $i.FullName -force -ErrorVariable errVar -ErrorAction SilentlyContinue
...
...
最佳答案
所以你可以使用Select -first $Limit
其次,无需排除文件夹$i.PSIsContainer
,您可以告诉Get-ChildItem
(别名GCI
)仅使用-File
参数获取文件
就像是
function Remove-ChildItemsInChunks($keepForDays, $Limit, $Path){
$count = 0
gci $Path -Recurse -File |
?{$i.LastWriteTime -lt ($(Get-Date).AddDays(-$keepForDays))} |
select -First $Limit | %{
$count += 1
Remove-Item $_
}
return $Count
}
$GCICount = Get-ChildItemsInChunks -Path C:\test -keepForDays 30 -Limit 500
while($GCICount -gt 0){
$GCICount = Get-ChildItemsInChunks -Path C:\Test -keepForDays 30 -Limit 500
}
关于powershell - 能做到吗根据文件使用Powershell的年代删除大量文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463364/