首页 > 解决方案 > 如何使用PowerShell删除目录中的所有文件以及小于100kb的所有子目录

问题描述

我有一个包含数千个子目录的目录,我试图删除所有小于 100 kb 的文件。我写了以下脚本;但是,它会删除子目录,而不是删除其中的单个文件。

#root directory
$dir = "D:\S3\images"

#minimum size for file
$minSize = 100

#go through every item in the root directory
Get-ChildItem -Path $dir -Recurse | ForEach-Object {
#check if file length is less than 100kb 
  if ($_.Length / 100kb -lt $minSize) {
    Remove-Item $_ -Force
  } else {
    #file is too big to remove
  }
}

我究竟做错了什么?

标签: powershellrecursionforeach

解决方案


我通过以下修复更正了脚本:

#root directory
$path = "D:\S3\images"

Get-ChildItem -Path $path -Include *.* -File -Recurse | ForEach-Object {
#check if file length is less than 100kb 
  if ($_.Length -lt 100kb) {
    Remove-Item $_ -Force
  } else {
    #file is too big to remove
  }
}

推荐阅读