Home > front end >  Powershell - Search Subfolders and delete smallest fles in each
Powershell - Search Subfolders and delete smallest fles in each

Time:12-31

I'm not sure if this would be considered a strange request, but I'm stuck on a script to search subfolders, and delete the smallest file from inside the folder.
I'm working with a folder structure along the lines of:

TopFolder
└─── folder1
│   │   file1.txt - 42kb
│   │   file2.txt - 84kb
|   |
└─── folder2
    │   file1.txt - 83kb
    │   file2.txt - 34kb
...

I'm looking to find a way to recursively go through all the subfolders under the "TopFolder", find the smallest file in each of the folders, delete it, then continue to next folder.

I tried something along the lines of the following, but it's giving me "item doesn't exist" errors

Get-ChildItem -Recurse -Directory -Path 'Z:\TopFolder' |
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
    }

CodePudding user response:

Change: Get-ChildItem -File -Path $_ to $_ | Get-ChildItem -File – Mathias R. Jessen

Worked, perfect, thank you.

CodePudding user response:

An alternative to what you're trying to accomplish, in case you need to enumerate many files and directories this should be faster:

using namespace System.IO

$topFolder = 'Z:\TopFolder'
$enum = [EnumerationOptions]::new()
$enum.RecurseSubdirectories = $true
$directories = [Directory]::GetDirectories($topFolder, '*', $enum)

foreach($dir in $directories)
{
    $todelete = [FileInfo[]][Directory]::GetFiles(
        $dir, '*', $enum
    ) | Sort-Object Length | Select-Object -First 1

    if($todelete)
    {
        Remove-Item $todelete -WhatIf
    }
}

Note, above assumes you're not looking to find hidden or system files / folders. If you actually want to search for them you would need to use this instead:

$enum.AttributesToSkip = 0
  • Related