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

标签 powershell recursion foreach

我有包含数千个子目录的目录,我正在尝试删除所有小于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
  }
}
我究竟做错了什么?

最佳答案

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

Get-ChildItem -File -Path $dir -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
  }
}

关于powershell - 如何使用PowerShell删除目录中的所有文件和所有小于100kb的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63471130/

相关文章:

c - 二叉树遍历导致堆栈溢出

php - 对象 LimitIterator - OutOfBoundsException

c# - ForEach循环到txt

events - 在 PowerShell 中订阅对象的静态事件的语法是什么?

azure - 使用逻辑应用创建具有关键字 "Keyword2"和 "Keyword2"的新 AD 组时配置警报

sql - 使用CTE的相邻列表和递归查询,如何回填?

PHP foreach & 在特定时间运行

powershell - 无法将默认终端设置为 PowerShell 6.0

用于设置 pagefile.sys 大小的 PowerShell 脚本

c - 我该如何修复这个 (is_sorted) 递归函数?