Skip to content

Instantly share code, notes, and snippets.

@manualbashing
Last active July 8, 2024 15:15
Show Gist options
  • Select an option

  • Save manualbashing/b1ba96870f8c7b2b78567f4bc160c510 to your computer and use it in GitHub Desktop.

Select an option

Save manualbashing/b1ba96870f8c7b2b78567f4bc160c510 to your computer and use it in GitHub Desktop.
Get files from Azure file share recursively

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-AzStorageFile on 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
published: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment