【问题标题】:How do I delete sub-directory regardless of parent folder name using powershell?无论使用powershell的父文件夹名称如何,如何删除子目录?
【发布时间】:2022-10-07 22:46:05
【问题描述】:

PS脚本新手,请多多包涵。

我有以下文件夹结构 - D:\Folder1、Folder2、Folder3.... 每个父文件夹都有相同的子文件夹结构,使用 yyyymmdd 格式(D:\Folder1\20221007)。我想使用 PS 删除这些子文件夹中任何超过 90 天的文件夹。我们一直在添加/删除父文件夹。我正在使用下面的脚本,但由于父文件夹更频繁地更改,它变得难以管理。我在想我可以列出所有父文件夹并将它们传入然后循环,但不确定如何最好地做到这一点。如果可能的话,我还想写下所有被删除文件夹的完整路径。

$DaysAgo = (Get-Date).AddMonths(-3)
$Folders = (Get-ChildItem "D:\Folder1" | Where-Object {$_.PSIsContainer -Eq $True -And $_.Name -Match '^\d{8}'})
ForEach ($f In $Folders) {
    $FolderDate = Get-Date -Year $f.Name.SubString(0,4) -Month $f.Name.SubString(4,2) -Day $f.Name.SubString(6,2)
    If ($FolderDate -LT $DaysAgo) {
        Remove-Item $f.FullName -Recurse
    }
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    干得好:

    $DaysAgo = (Get-Date).AddMonths(-3)
    #Specify the switch parameter "-Directory", so get-childitem will only return directories. Also you can filter on the creation date of the directory
    $Folders = Get-ChildItem -Directory -Path "D:Folder1" | Where-Object {$_.Name -Match '^d{8}' -and $_.CreationTime -lt $DaysAgo}
    #You can pass all paths to the parameter -path
    $null = Remove-Item -Path $Folders.FullName -Confirm:$false -Force -recurse
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 2011-04-08
      • 2018-11-13
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多