首页 > 解决方案 > 如果 *.tmp 存在于其中的任何位置,如何不对目录进行操作?

问题描述

此代码应遍历当前目录中的所有顶级目录,执行临时文件检查,如果不存在则移动目录。

$processDirectories = {
    foreach ($childDirectory in Get-ChildItem -Force -Directory) {
        test-path "$childDirectory\*.tmp"
        move-item -LiteralPath "$childDirectory" -Destination "d:\"
    }
}

我不知道如何停止运行*.tmp找到的目录的代码。此外,此方法仅检查每个子目录的根,*.tmp而不是其中的整个树。

标签: powershellpowershell-4.0

解决方案


如果我了解您的限制,这里有两个变体,
计算*.tmp子文件夹中的数量。如果为零,则移动项目文件夹。

  1. 迭代第一级文件夹

    foreach ($childDirectory in Get-ChildItem -Force -Directory) {
      if ((Get-ChildItem $childDirectory -recurse -Include *.tmp, *.!qb).Count -eq 0){
        Move-Item -LiteralPath "$childDirectory" -Destination "d:\" -WhatIf
      }
    }
    
  2. 单一管道

    Get-ChildItem -Force -Directory | Where-Object {
      (Get-ChildItem $_ -recurse -Include *.tmp, *.!qb).Count -eq 0} |
        Move-Item -Destination "d:\" -WhatIf
    

如果输出看起来正常,请删除尾随-WhatIf


推荐阅读