* .tmp是否存在于目录中,如何不对其进行操作?

时间:2019-05-11 17:52:17

标签: powershell powershell-v4.0

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

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

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

2 个答案:

答案 0 :(得分:2)

只需使用if

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

关于子目录,请使用-Recurse的{​​{1}}开关。

答案 1 :(得分:2)

如果我了解您的限制,这里有两个变体,
计算子文件夹中*.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