PowerShell递归删除目录中小于500字节的文件

PowerShell Remove Files smaller than 500bytes in directory recursively

我需要一个脚本来递归删除文件夹中扩展过滤器为 .stat 且所有文件都小于 500 字节的所有文件。

如果脚本能先给我所有文件和将要删除的文件数,然后按回车键继续删除所有文件,那就太好了。

使用 Get-Childitem 非常简单,对 Where-Object 和 ForEach-Object 有帮助:

$path = 'some path defined here'
Get-ChildItem $path -Filter *.stat -recurse |?{$_.PSIsContainer -eq $false -and $_.length -lt 500}|?{Remove-Item $_.fullname -WhatIf}

测试后删除 -whatif 以确保代码删除了您想要的文件。

如果您有大量子文件夹要递归,那么您可能想尝试 Get-ChildItem 的 -file 开关,因为使用文件系统提供程序进行过滤比使用 Where-Object 更有效。

Get-ChildItem $path -Filter *.stat -recurse -file | ? {$_.length -lt 500} | % {Remove-Item $_.fullname -WhatIf}

更简单的解决方案:

ls | where {$_.Length -lt .0.0005mb} | Remove-Item -Force-Recurse