Warm tip: This article is reproduced from serverfault.com, please click

recursion-在Powershell中过滤和删除早于x天的文件和文件夹(以及文件夹内的文件)

(recursion - Filter and delete files and folders(and files inside of folders) older than x days in powershell)

发布于 2020-11-30 11:28:17

这是我在这个论坛上的第一篇文章。我是编码的初学者,我需要第一个自编码工具的帮助。我做了一个小脚本,该脚本会根据文件是否早于日期x(lastwritetime)删除文件。现在是我的问题:我还希望脚本还检查目录中文件夹内的文件,然后仅在文件夹真正为空时才删除它。我无法弄清楚如何解决此问题中的递归,似乎脚本删除了相对于日期x的整个文件夹。谁能告诉我我在这段代码中缺少的内容,并帮助我创建自己的递归来解决问题或修复代码?谢谢大家!这是我的代码:

如果有人知道如何通过使用函数使代码正常工作,我将感到非常高兴


$path = Read-Host "please enter your path"
"
"

$timedel = Read-Host "Enter days in the past (e.g -12)"

$dateedit = (Get-Date).AddDays($timedel)
"
"
Get-ChildItem $path -File -Recurse | foreach{ if ($_.LastWriteTime -and !$_.LastAccessTimeUtc -le $dateedit) {

Write-Output "older as $timedel days: ($_)" } }

" 
"
pause

Get-ChildItem -Path $path -Force -Recurse | Where-Object { $_.PsisContainer -and $_.LastWriteTime -le $dateedit } | Remove-Item -Force -Recurse 

""
Write-Output "Files deleted"
Questioner
xjustinx000
Viewed
11
Алексей Семенов 2020-11-30 21:23:37
param(
    [IO.DirectoryInfo]$targetTolder = "d:\tmp",
    [DateTime]$dateTimeX = "2020-11-15 00:00:00"
)

Get-ChildItem $targetTolder -Directory -Recurse | Sort-Object {$_.FullName} -Descending | ForEach-Object {
    Get-ChildItem $_ -File | Where-Object {$_.LastWriteTime -lt $dateTimeX} | Remove-Item -Force
    if ((Get-ChildItem $_).Count -eq 0){Remove-Item $_ -Force} 
}

测试后删除-WhatIf