删除所有文件和文件夹工作非常慢



我需要删除所有超过 15 天的存档文件和文件夹。

我已经使用PowerShell脚本实现了该解决方案,但是删除所有文件需要一天多的时间。文件夹的总大小小于 100 GB。

$StartFolder = "\GuruArchive"
$deletefilesolderthan = "15"
#Get Foldernames for ForEach Loop
$SubFolders = Get-ChildItem -Path $StartFolder |
Where-Object {$_.PSIsContainer -eq "True"} |
Select-Object Name
#Loop through folders
foreach ($Subfolder in $SubFolders) {
Write-Host "Processing Folder:" $Subfolder
#For each folder recurse and delete files olders than specified number of days while the folder structure is left intact.
Get-ChildItem -Path $StartFolder$($Subfolder.name) -Include *.* -File -Recurse |
Where LastWriteTime -lt (Get-Date).AddDays(-$deletefilesolderthan) |
foreach {$_.Delete()}
#$dirs will be an array of empty directories returned after filtering and loop until until $dirs is empty while excluding "Inbound" and "Outbound" folders.
do {
$dirs = gci $StartFolder$($Subfolder.name) -Exclude Inbound,Outbound -Directory -Recurse |
Where {(gci $_.FullName).Count -eq 0} |
select -ExpandProperty FullName
$dirs | ForEach-Object {Remove-Item $_}
} while ($dirs.Count -gt 0)
}
Write-Host "Completed" -ForegroundColor Green
#Read-Host -Prompt "Press Enter to exit"

请提出一些优化性能的方法。

如果有许多较小的文件,则较长的删除时间并不异常,因为它必须处理每个文件描述符。 根据您的版本,可以进行一些改进;我假设你至少在v4上。

#requires -Version 4
param(
[string]
$start = '\GuruArchive',
[int]
$thresholdDays = 15
)
# getting the name wasn't useful. keep objects as objects
foreach ($folder in Get-ChildItem -Path $start -Directory) {
"Processing Folder: $folder"
# get all items once
$folders, $files = ($folder | Get-ChildItem -Recurse).
Where({ $_.PSIsContainer }, 'Split')
# process files
$files.Where{
$_.LastWriteTime -lt (Get-Date).AddDays(-$thresholdDays)
} | Remove-Item -Force
# process folders
$folders.Where{
$_.Name -notin 'Inbound', 'Outbound' -and
($_ | Get-ChildItem).Count -eq 0
} | Remove-Item -Force
}
"Complete!"

花费如此多时间的原因是您要通过网络删除文件/文件夹,这导致每个文件和文件夹都需要额外的网络通信。您可以使用网络分析器轻松检查该事实。这里最好的方法是使用允许运行在远程计算机上执行文件操作的代码的方法之一,例如,您可以尝试使用:

  1. 赢瑞
  2. psexec(首先将代码复制到远程计算机,然后使用psexec执行它)
  3. 远程 WMI(使用 CIM_Datafile)
  4. 甚至将所需的任务添加到调度程序中

我更喜欢使用 WinRM,但 psexec 也是一个不错的决定(如果您不想执行 WinRM 的其他配置)。

最新更新