如何删除文件夹和文件目录中除最新文件以外的所有文件

How to delete all but the most recent files in a directory of folders and files

我有一个文件夹,里面有一堆按文件夹分隔的备份。我想要一个脚本来使用目录 (C:\Users\user\Desktop\TEST) 并且在该目录中我有任意数量的文件夹,其中包含任意数量的文件,我只想为文件夹中的每个文件夹保留最新的文件夹目录并删除其余部分。

我有这个,但它一次只能处理 1 个文件夹,而且必须进行硬编码。

$path = "C:\Users\user\Desktop\TEST\Folder1"
$FileNumber = (get-childitem $path).count - 1
get-childitem -path $path | sort CreationTime -Descending | select -last $FileNumber |  Remove-Item -Force -WhatIf

有什么方法可以自动化吗?

谢谢,

你可以试试这个:

$Path = "C:\Users\user\Desktop\TEST"
$Folders = Get-ChildItem $Path
foreach ($Folder in $Folders)
{
    $FolderName = $Folder.FullName
    $Files = Get-ChildItem -Path $FolderName
    $FileNumber = $Files.Count - 1
    $Files | sort CreationTime -Descending | select -last $FileNumber | Remove-Item -Force -WhatIf
}

您需要选择一个循环来完成此操作,此示例使用 ForEach-Object. Instead of using Select-Object -Last N you could just use Select-Object -Skip 1 to skip the newest file. Also note the use of -Directory and -File with Get-ChildItem 仅过滤目录或仅过滤文件。

$path = "C:\Users\user\Desktop\TEST\Folder1"

# Get all Directories in `$path`
Get-ChildItem $path -Directory | ForEach-Object {
    # For each Directory, get the Files
    Get-ChildItem $_.FullName -File |
        # Sort them from Newest to Oldest
        Sort-Object CreationTime -Descending |
        # Skip the first 1 (the newest)
        Select-Object -Skip 1 |
        # Remove the rest
        Remove-Item -Force -WhatIf
}