【问题标题】:Powershell - Search Subfolders and delete smallest fles in each [duplicate]Powershell - 搜索子文件夹并删除每个[重复]中的小文件
【发布时间】:2021-12-31 08:06:28
【问题描述】:

我不确定这是否会被视为一个奇怪的请求,但我被困在搜索子文件夹并从文件夹中删除最小文件的脚本上。
我正在使用以下文件夹结构:

TopFolder
└─── folder1
│   │   file1.txt - 42kb
│   │   file2.txt - 84kb
|   |
└─── folder2
    │   file1.txt - 83kb
    │   file2.txt - 34kb
...

我正在寻找一种方法来递归遍历“TopFolder”下的所有子文件夹,找到每个文件夹中最小的文件,将其删除,然后继续下一个文件夹。

我尝试了以下内容,但它给了我“项目不存在”错误

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
    }

【问题讨论】:

  • Get-ChildItem -File -Path $_ 更改为$_ | Get-ChildItem -File
  • 嗯,这很尴尬。非常感谢。
  • 你在哪里确定最小的文件?
  • Nvm,没看到length属性排序;)
  • 问题是 Windows PowerShell 有时仅按文件 name 而不是按完整路径Get-ChildItem 输出对象进行字符串化>,取决于Get-ChildItem 的调用方式;该问题已在 PowerShell (Core) v6.1+ 中得到修复。解决方法是使用.FullName 来确保使用完整路径,或者,如果要将对象传递给其他文件处理cmdlet,则通过管道 传递它们。详情请见this answer

标签: powershell


【解决方案1】:

更改:Get-ChildItem -File -Path $_$_ | Get-ChildItem -File – 马蒂亚斯·R·杰森

工作,完美,谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多