代码之家  ›  专栏  ›  技术社区  ›  user1753362

Powershell-删除旧文件夹但不删除旧文件

  •  0
  • user1753362  · 技术社区  · 9 年前

    我有以下代码要保留在我不再想保留的旧文件夹上

         Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue| 
          Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } |
           Remove-Item -Force -EA SilentlyContinue
         Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue| 
          Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path 
           $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) 
           -eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
    

    它删除任何超过一定天数的内容 (美元限额) 包括文件和文件夹。 然而,我所追求的只是删除旧文件夹及其内容。

    例如,一个一天的文件夹中可能有一年前的文件,但我想保留该文件夹和旧文件。上面的代码保留了文件夹,但删除了文件。我只想删除根目录中比 $限额 否则,就别管其他文件夹和内容了。

    提前谢谢。

    1 回复  |  直到 9 年前
        1
  •  0
  •   Deadly-Bagel    9 年前

    看看这一点:

     Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue| 
      Where-Object { !$_.PSIsContainer -and $_.CreationTime -ge $limit } |
       Remove-Item -Force -EA SilentlyContinue
    

    它基本上是说“所有不是文件夹并且比指定的旧的内容都被删除”。所以你的第一步是去除它。

    第二部分只是删除空文件夹,您可以保持原样,也可以添加到Where语句中以包含CreationTime:

     Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue| 
      Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit -and (Get-ChildItem -Path 
       $_.FullName -Recurse -Force | Where-Object { $_.CreationTime -lt $limit }) 
       -eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
    

    第二个Where语句返回一个比$limit更新的文件和文件夹列表,如果该列表为空,则仅删除该文件夹。