如果文件夹是空的,还要删除比过去设置的日期更早的文件夹,这会给您带来这样的问题,即一旦从此类文件夹中删除文件,文件夹的 LastWriteTime 就会被设置为该时刻。
这意味着您应该先获取旧文件夹列表,然后再开始删除旧文件,然后使用该列表删除这些文件夹(如果它们为空)。
此外,应该对来自 Read-Host 的用户输入进行最低限度的检查。(即路径必须存在并且天数必须可转换为整数。对于后者,我选择简单地将其转换为,[int]
因为如果失败,代码无论如何都会生成一个执行。
尝试类似的东西
$path = Read-Host "please enter your path"
# test the user input
if (-not (Test-Path -Path $path -PathType Container)) {
Write-Error "The path $path does not exist!"
}
else {
$timedel = Read-Host "Enter days in the past (e.g -12)"
# convert to int and make sure it is a negative value
$timedel = -[Math]::Abs([int]$timedel)
$dateedit = (Get-Date).AddDays($timedel).Date # .Date sets this date to midnight (00:00:00)
# get a list of all folders (FullNames only)that have a LastWriteTime older than the set date.
# we check this list later to see if any of the folders are empty and if so, delete them.
$folders = (Get-ChildItem -Path $path -Directory -Recurse | Where-Object { $_.LastWriteTime -le $dateedit }).FullName
# get a list of files to remove
Get-ChildItem -Path $path -File -Recurse | Where-Object { $_.LastWriteTime -le $dateedit} | ForEach-Object {
Write-Host "older as $timedel days: $($_.FullName)"
$_ | Remove-Item -Force -WhatIf # see below about the -WhatIf safety switch
}
# now that old files are gone, test the folder list we got earlier and remove any if empty
$folders | ForEach-Object {
if ((Get-ChildItem -Path $_ -Force).Count -eq 0) {
Write-Host "Deleting empty folder: $_"
$_ | Remove-Item -Force -WhatIf # see below about the -WhatIf safety switch
}
}
Write-Host "All Done!" -ForegroundColor Green
}
Remove-Item 上使用的-WhatIf
开关是为了您自己的安全。这样,实际上不会删除任何文件或文件夹,而是在控制台中写入将要删除的内容。如果您对这一切都感到满意,请删除-WhatIf
并再次运行代码以真正删除文件和文件夹