如何使用PowerShell删除目录中的所有文件以及小于100kb的所有子目录

如何使用PowerShell删除目录中的所有文件以及小于100kb的所有子目录,powershell,recursion,foreach,Powershell,Recursion,Foreach,我有一个包含数千个子目录的目录,我正试图删除所有大小小于100KB的文件。我写了以下脚本;但是,它会删除子目录,而不是删除其中的单个文件 #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-Obje

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

#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
  }
}

我做错了什么?

您的长度检查不正确,您不需要进行除法。此外,您可能希望使用
-File
参数跳过
Get-ChildItem
中的目录

尝试:


我使用以下修复程序更正了脚本:

#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
  }
}

好的,我第一次在测试目录上运行它时,它就工作了,现在我得到了一个
找不到路径
错误。这条路是明确的。
#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
  }
}