简体   繁体   中英

How to delete the smallest file in a directory recursively?

Example: there are two directories in the root folder:

 "Root folder" wishfull_script_to_delete_small_files.BAT "SubFolder_One" test1.txt.......... 1 kb test2.txt.......... 1.1 kb "SubFolder_Two" picture001.jpg..... 34 kb picture002.jpg..... 64 kb

So I want to automatically delete test1.txt and picture001.jpg but not the script (batch) itself (probably is going to be the smallest file).

If you are setting out to learn something, PowerShell is a far more capable tool than cmd.exe . It is available on all supported Windows systems. When written correctly, the same code can run unchanged on UNIX, Linux, and Mac systems.

Once you are confident that the correct files will be removed, remove the -WhatIf from the Remove-Item command.

Get-ChildItem -Recurse -Directory -Path 'C:\src\t' |
    ForEach-Object {
        Get-ChildItem -File -Path $_ |
            Where-Object { $_.Name -ne $(Split-Path -Path $PSCommandPath -Leaf) } |
            Sort-Object -Property Length |
            Select-Object -First 1 |
            Remove-Item -WhatIf
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM