【问题标题】:PowerShell Script to Delete files from all SubFolders which are older than 30 days用于从所有子文件夹中删除超过 30 天的文件的 PowerShell 脚本
【发布时间】:2020-01-04 20:20:58
【问题描述】:

我想从下面的文件夹结构中删除所有类型的文件,这些文件早于 30 天。所以我使用了下面的 PowerShell 脚本。但它不会删除任何文件。

PowerShell 脚本:

Get-ChildItem –Path  "C:\Users\VJ\Documents\MainDir" –Recurse | Where-Object { $_.CreationTime –lt (Get-Date).AddDays(-30) } | Remove-Item

文件夹结构:

  MainDir
     |
  SubDir1 -> Folder1 -> Folder2 -> Zip/CSV files 
  SubDir2 -> Folder1->.txt files
               |
              Folder2 -> .txt files

最终结果应该是从所有文件夹(MainDir 的子文件夹)中删除的所有类型的文件。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    认为您混淆了CreationTimeLastWriteTime 的属性。

    如果您刚刚将(旧)文件复制到结构中的目录之一,CreationTime 是文件复制到那里的日期和时间,可以是今天。但是,LastWriteTime 属性显示文件上次写入的日期和时间。

    试试:

    $refDate = (Get-Date).AddDays(-30)
    Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse -File | 
        Where-Object { $_.LastWriteTime -lt $refDate } | 
        Remove-Item -Force
    

    如果您使用的 PowerShell 版本低于 3.0,请使用:

    Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse | 
        Where-Object { !$_.PSIsContainer -and  $_.LastWriteTime -lt $refDate } | 
        Remove-Item -Force
    

    另外,检查并重新输入破折号,因为它们可能看起来像普通连字符,实际上它们是 EN Dashes(十六进制值 2013;十进制 8211)

    希望有帮助

    【讨论】:

    • 感谢@Theo 成功了。但是如何在单个 PowerShell 脚本中为另一个文件夹添加相同的命令?多个文件夹的单个脚本。
    • @VikasJ Get-ChildItem-Path 参数可以采用路径数组。所以你可以做Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir", "C:\Users\VJ\Documents\SecondaryDir" -Recurse等。
    【解决方案2】:

    试试这个:

    Get-ChildItem -Path "C:\Users\VJ\Documents\MainDir" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime –lt (Get-Date).AddDays(-30) } | Remove-Item -Force

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 2023-01-17
      • 2022-07-06
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多