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

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

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

this is my first post on this forum. Im a beginner in coding and I need help with one of my very first self coded tools. I made a small script, which deletes files based on if they are older than date x (lastwritetime). Now to my problem: I want the script also to check for files inside of folders inside of a directory and only delete a folder afterwards if it is truly empty. I cant figure out how to solve the recursion in this problem, seems like the script deletes just the entire folder in relation to the date x. Could anyone tell me please what I missed in this code and help me to create a own recursion to solve the problem or fix the code? Thanks to you all, guys! Here is my code:

I would be glad if someone knows how to make the code work by using a function


$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
0
Алексей Семенов 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} 
}

remove -WhatIf after test