debastiti
debastiti

Reputation: 1

Delete empty folders in azure file share storage using powershell script

I'm using the script below in order to delete all the files in an Azure File Share Storage that are older than 30 days. But now there are several empty folders and subfolders in this File Share Storage, is there a way to delete these empty folders/subfolders that I can add to the script?

$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $key
 $shareName = <shareName>
    
 $DirIndex = 0
 $dirsToList = New-Object System.Collections.Generic.List[System.Object]
    
 # Get share root Dir
 $shareroot = Get-AzStorageFile -ShareName $shareName -Path . -context $ctx 
 $dirsToList += $shareroot 
    
 # List files recursively and remove file older than 30 days 
 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)
     {
         # Fetch Attributes of each file and output
         $task = $file.CloudFile.FetchAttributesAsync()
         $task.Wait()
    
         # remove file if it's older than 30 days.
         if ($file.CloudFile.Properties.LastModified -lt (Get-Date).AddDays(-30))
         {
             ## print the file LMT
             # $file | Select @{ Name = "Uri"; Expression = { $_.CloudFile.SnapshotQualifiedUri} }, @{ Name = "LastModified"; Expression = { $_.CloudFile.Properties.LastModified } } 
    
             # remove file
             $file | Remove-AzStorageFile
         }
     }
     #Debug log
     # Write-Host  $DirIndex $dirsToList.Length  $dir.CloudFileDirectory.SnapshotQualifiedUri.ToString() 
 }

Code credits: https://learn.microsoft.com/en-us/answers/questions/482814/deleting-files-in-azure-file-share-older-than-x-da.html

Upvotes: 0

Views: 651

Answers (1)

yxc
yxc

Reputation: 151

you already got all directories in $dirsListOut, just create another foreach loop and delete them with Remove-AzureStorageDirectory

Upvotes: 0

Related Questions