1

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
    }
  • 1
    Change `Get-ChildItem -File -Path $_` to `$_ | Get-ChildItem -File` – Mathias R. Jessen Dec 30 '21 at 22:52
  • Well, that's embarassing. Thank you very much. – ArcTech.Nerd Dec 30 '21 at 22:53
  • Where exactly are you determining the smallest file? – Abraham Zinala Dec 30 '21 at 23:11
  • Nvm, I didn't see the length property sorting;) – Abraham Zinala Dec 30 '21 at 23:34
  • The problem is that _Windows PowerShell_ sometimes stringifies `Get-ChildItem` output objects by file _name_ only rather than by _full path_, _depending on how `Get-ChildItem` was invoked_; the problem has been fixed in _PowerShell (Core) v6.1+_. The workaround is to use `.FullName` to ensure use of the full path or, if the objects are to be passed to other file-processing cmdlets, to pass them _via the pipeline_. See [this answer](https://stackoverflow.com/a/53400031/45375) for details. – mklement0 Dec 31 '21 at 01:28

1 Answers1

2

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

Worked, perfect, thank you.