使用 Powershell 递归删除文件
Deleting files with Powershell recursively
我遇到了一个奇怪的问题,我正在尝试使用一个过程自动删除文件夹和子文件夹中的文件,我试图只删除超过 7 天的文件。
我的代码有效,但它会在递归进入子项时删除 7 天以内的文件。 . .anyone 可以在这里伸出援手吗?我只需要在每个 folder/sub-folder 中删除超过 7 天的文件。
Param (
[string]$Source = "C:\Users\Loredanes\Downloads\",
[string]$Days = "1"
)
$Files = Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).addminutes(-$($Days)) }
$Files | Remove-Item -Force
if ($Files.count -gt 0)
{
$Folders = @()
ForEach ($Folder in (Get-ChildItem -Path $Source -Recurse -Directory))
{
$Folders += New-Object PSObject -Property @{
Object = $Folder
Depth = ($Folder.FullName.Split("\")).Count
}
}
$Folders = $Folders | Sort Depth -Descending
ForEach ($Folder in $Folders)
{
If ($Folder.Object.GetFileSystemInfos().Count -eq 0)
{
Write-Host "Removing Folder: $($Folder)"
Remove-Item -Path $Folder.Object.FullName -Force
}
}
}
else
{
Write-Host "No Empty folders found after removing files older than $($Days) days."
}
这应该可以满足您的要求:
$source = 'D:\Test'
$days = 7
# Remove Files
Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).AddDays(-$($days)) } | % { Remove-Item -Path $_.FullName -Force }
# Remove empty directories
Get-ChildItem $source -Recurse | Where-Object { $_.PSIsContainer -and $_.GetFiles("*.*").Count -le 0 } | % { Remove-Item -Path $_.FullName -Force }
我遇到了一个奇怪的问题,我正在尝试使用一个过程自动删除文件夹和子文件夹中的文件,我试图只删除超过 7 天的文件。
我的代码有效,但它会在递归进入子项时删除 7 天以内的文件。 . .anyone 可以在这里伸出援手吗?我只需要在每个 folder/sub-folder 中删除超过 7 天的文件。
Param (
[string]$Source = "C:\Users\Loredanes\Downloads\",
[string]$Days = "1"
)
$Files = Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).addminutes(-$($Days)) }
$Files | Remove-Item -Force
if ($Files.count -gt 0)
{
$Folders = @()
ForEach ($Folder in (Get-ChildItem -Path $Source -Recurse -Directory))
{
$Folders += New-Object PSObject -Property @{
Object = $Folder
Depth = ($Folder.FullName.Split("\")).Count
}
}
$Folders = $Folders | Sort Depth -Descending
ForEach ($Folder in $Folders)
{
If ($Folder.Object.GetFileSystemInfos().Count -eq 0)
{
Write-Host "Removing Folder: $($Folder)"
Remove-Item -Path $Folder.Object.FullName -Force
}
}
}
else
{
Write-Host "No Empty folders found after removing files older than $($Days) days."
}
这应该可以满足您的要求:
$source = 'D:\Test'
$days = 7
# Remove Files
Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).AddDays(-$($days)) } | % { Remove-Item -Path $_.FullName -Force }
# Remove empty directories
Get-ChildItem $source -Recurse | Where-Object { $_.PSIsContainer -and $_.GetFiles("*.*").Count -le 0 } | % { Remove-Item -Path $_.FullName -Force }