Imagine you have a policy to not keep files on an azure file share that are older than a specified time, lets say 5 days.
The Az.Storage powershell module provides the cmdlet Get-AzStorageFile that can be used to retrive the files from an Azure file share, but there are two shortcomings of this cmdlet, that makes our task a bit difficult (at least in the module's current version when writing this article: 5.1.0):
- Files are not retrieved recursively. If you hit a folder, you need to call
Get-AzStorageFileon this folder, if you want to list it's content. - File properties like LastModified are not retrieved. You need to manually call the
FetchAttributes()method to fill this attributes with value.
Fortunately PowerShell 7 makes it relatively easy to address both problems with a simple wrapper function:
function Get-AzStorageFileRecursively {
Get-AzStorageFile @Args @PSBoundParameters |
ForEach-Object {
# This is necessary to provide "Properties.LastModified"
$_.FetchAttributes()
Write-Output $_
if ($_.GetType() -match 'CloudFileDirectory') {
Get-AzStorageFileRecursively -Directory:$_
}
}
} Wrapped that way we solve our task to remove files, that are older than 5 days in a straight forward way:
# Get all files from the fileshare that are at least 5 days old
Get-AzStorageFileRecursively -ShareName 'share' -StorageContext $sa.Context |
Where-Object { $_.GetType() -NotMatch 'Directory' -and $_.Properties.LastModified -le (Get-Date).AddDays(-5) } |
Remove-AzStorageFile