|
# 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 |