You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Azure文件存储的PowerShell清理脚本添加删除空文件夹功能

给Azure文件存储清理脚本添加空文件夹删除逻辑

当然可以,只需要在原有脚本基础上添加从下往上遍历删除空文件夹的逻辑就行——因为空文件夹必须先删子文件夹再删父文件夹,不能从上到下直接处理。

以下是修改后的完整脚本,保留了原有的旧文件删除逻辑,新增了空文件夹清理部分:

$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $key
$shareName = <shareName>

$DirIndex = 0
$dirsToList = New-Object System.Collections.Generic.List[System.Object]

# 获取共享根目录
$shareroot = Get-AzStorageFile -ShareName $shareName -Path . -context $ctx 
$dirsToList += $shareroot 

# 递归列出文件并删除30天前的旧文件
While ($dirsToList.Count -gt $DirIndex)
{
    $dir = $dirsToList[$DirIndex]
    $DirIndex ++
    $fileListItems = $dir | Get-AzStorageFile
    $dirsListOut = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFileDirectory"}
    $dirsToList += $dirsListOut
    $files = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFile"}

    foreach($file in $files)
    {
        # 获取文件属性
        $task = $file.CloudFile.FetchAttributesAsync()
        $task.Wait()

        # 删除30天前的文件
        if ($file.CloudFile.Properties.LastModified -lt (Get-Date).AddDays(-30))
        {
            $file | Remove-AzStorageFile
        }
    }
}

# -------------------------- 新增:删除空文件夹逻辑 --------------------------
# 逆序遍历文件夹列表(从最深层子文件夹开始)
for ($i = $dirsToList.Count - 1; $i -ge 0; $i--) {
    $currentDir = $dirsToList[$i]
    # 跳过根目录,避免误删共享根
    if ($currentDir.CloudFileDirectory.Name -eq [string]::Empty) {
        continue
    }

    # 获取当前文件夹下的所有项
    $dirItems = $currentDir | Get-AzStorageFile
    $hasFiles = $dirItems | Where-Object {$_.GetType().Name -eq "AzureStorageFile"} | Measure-Object | Select-Object -ExpandProperty Count
    $hasSubDirs = $dirItems | Where-Object {$_.GetType().Name -eq "AzureStorageFileDirectory"} | Measure-Object | Select-Object -ExpandProperty Count

    # 如果既没有文件也没有子目录,删除该空文件夹
    if ($hasFiles -eq 0 -and $hasSubDirs -eq 0) {
        Write-Host "删除空文件夹: $($currentDir.CloudFileDirectory.SnapshotQualifiedUri)"
        $currentDir | Remove-AzStorageFileDirectory
    }
}

关键修改说明

  • 逆序遍历文件夹:原有脚本已经把所有文件夹存入$dirsToList列表,逆序遍历能确保先处理最深层的子文件夹,这样父文件夹在子文件夹被删除后才会被判定为空。
  • 跳过根目录:根目录的名称为空字符串,跳过它可以避免误删整个文件共享的根目录。
  • 空文件夹判定:统计当前文件夹下的文件数量和子目录数量,两者都为0时判定为空,执行删除操作。

内容的提问来源于stack exchange,提问作者debastiti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:01:03