Skip to content

Instantly share code, notes, and snippets.

@silverl
Created March 21, 2023 22:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save silverl/e96d28321b20e96e6d95a6d5b4b603a9 to your computer and use it in GitHub Desktop.
Recursively removes Azure Storage File Share files using the Az.Storage module
# Log in first using Connect-AzAccount
param(
[string]$DirectoryPath,
[string]$StorageAccountName,
[string]$FileShareName,
[string]$ResourceGroupName,
[int]$DaysOld
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
# Get the current date
$CurrentDate = Get-Date
# Get the date to delete files older than
$DateToDelete = $CurrentDate.AddDays(-$DaysOld)
$StorageAccount = Get-AzStorageAccount -Name $StorageAccountName -ResourceGroupName $ResourceGroupName
# Create a storage context
$StorageContext = $StorageAccount.Context
# Define a function to recursively delete files in a directory
function Remove-FilesRecursively {
# Get the directory path from the first argument
$DirectoryPath = $Args[0]
Write-Output "Entering $DirectoryPath"
# Get all the files and directories in the directory
Get-AzStorageFile -ShareName $FileShareName -Path $DirectoryPath -Context $StorageContext | Get-AzStorageFile `
| ForEach-Object {
$Item = $_
$Item.Name
# If the item is a file, check if it is older than the date to delete and remove it if true
if ($Item.GetType().Name -eq "AzureStorageFile" -and $Item.LastModified -lt $DateToDelete) {
Write-Output "Removing $($Item.Name)"
$Item | Remove-AzStorageFile
}
# If the item is a directory, call this function recursively with its path as an argument
elseif ($Item.GetType().Name -eq "AzureStorageFileDirectory") {
Write-Output "Going into /$($DirectoryPath)/$($Item.Name)"
Remove-FilesRecursively "$($DirectoryPath)/$($Item.Name)" @PSBoundParameters
}
}
# Check if the directory is empty after deleting the files and directories inside it
$folder = Get-AzStorageFile -ShareName $FileShareName -Path $DirectoryPath -Context $StorageContext
$Contents = $folder | Get-AzStorageFile
if ($null -eq $Contents) {
Write-output "Removing empty folder $DirectoryPath"
$folder | Remove-AzStorageDirectory
}
}
# Call the function with an empty string as an argument to start from the root directory of the file share
Remove-FilesRecursively $DirectoryPath @PSBoundParameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment