Azure FileShare: Remove old files PowerShell

Azure File Share is a cloud-based file storage service in Microsoft Azure.

Azure File Share provides highly available, secure, and scalable storage for applications, services, and virtual machines running in the cloud or on-premises. It can be used for a variety of scenarios, including storing files for distributed applications, sharing files across different platforms and devices, and backing up data to the cloud.

With Azure File Share, users can easily store and share files in the cloud without the need for complex infrastructure or expensive hardware.

In this post we will be going through creating a script to report and if required remove files that are older than specific days.

First we need to get the storage account so we can use the context to query the file share.

Get-AzStorageAccount -ResourceGroupName name -Name storageac name

To get Azure file share there is no parameter to use resource group and storage account name so this is why we need to use context.

$sacontext = (Get-AzStorageAccount -ResourceGroupName Resourcegroup -StorageAccountName Name).Context
Get-AZStorageFile -Context $sacontext -ShareName sharename

To get the list of folders we can use the CloudFileDirectory property.

(Get-AZStorageFile -Context $sacontext -ShareName Name).CloudFileDirectory.Name

To get files we can use the CloudFile property.

(Get-AZStorageFile -Context $sacontext -ShareName operations-share).CloudFile

When checking the file properties most are blank.

To return the properties we need to fetch these using fetch attributes

$files = (Get-AZStorageFile -Context $sacontext -ShareName name).CloudFile

Once we have the properties we can create the script.

When running the script I have set two parameters. One to export to CSV and second one is to delete the files. If neither are set the script default out to the PowerShell console.

When using the -reportexport it will output to a csv file.

When using -delete the script will remove the files on the Azure file Share.

There is currently a bit of a limitation with Get-AZStorageFile command as it has no recursive parameter so going more than one folder down is difficult so this might not work for everyone.

The full script can be download from the below GitHub repository.