Skip to content

Instantly share code, notes, and snippets.

@MauricioZa
Created May 7, 2024 13:17
Show Gist options
  • Select an option

  • Save MauricioZa/9dcb2c85272bb914ffe8a04817089abb to your computer and use it in GitHub Desktop.

Select an option

Save MauricioZa/9dcb2c85272bb914ffe8a04817089abb to your computer and use it in GitHub Desktop.
Jim Kehoe File Expiration
# -----------------------------------------------------------------------------
# Initialise
# -----------------------------------------------------------------------------
#region Init
$resourceGroupName = "rg-FileExpiration"
$location = "eastus"
$StorageAccountName = "pwcfileexpiration"
$shareName = "share"
$numberOfDays = -1
$date = (Get-Date).AddDays(-30)
#endregion Init
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process
# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context
# Set and store subscription context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
#! Source Storage Account (hot file share)
# Get Source Storage Account Key
$accountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $StorageAccountName).Value[0]
$ctx = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $accountKey
$DirIndex = 0
$dirsToList = New-Object System.Collections.Generic.List[System.Object]
# Get share root Dir
$shareroot = Get-AzStorageFile -ShareName $shareName -Path . -context $ctx
$dirsToList += $shareroot
# List files recursively and remove file older than 14 days
While ($dirsToList.Count -gt $DirIndex)
{
$dir = $dirsToList[$DirIndex]
$DirIndex ++
$fileListItems = $dir | Get-AzStorageFile
$dirsListOut = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFileDirectory"}
$dirsToList += $dirsListOut
$files = $fileListItems | where {$_.GetType().Name -eq "AzureStorageFile"}
foreach($file in $files)
{
# Fetch Attributes of each file and output
$task = $file.CloudFile.FetchAttributesAsync()
$task.Wait()
# remove file if it's older than x number of days.
Write-Output "Checking file" $file.Name "with last modified date:" $file.CloudFile.Properties.LastModified
if ($file.CloudFile.Properties.LastModified -lt (Get-Date).AddDays($numberOfDays)){
# Remove file
Write-Output $file.CloudFile.SnapshotQualifiedUri.AbsoluteUri "is older than 1 days. Removing it."
$file | Remove-AzStorageFile
# Write the deleted file name to a CSV file
#$deletedFileName = $file.Name
#$csvFilePath = "C:\ARMMichael\deleted_files.csv"
#$deletedFileName | Export-Csv -Path $csvFilePath -Append -NoTypeInformation\
}
else {
# Keep the file
Write-Output $file.CloudFile.SnapshotQualifiedUri.AbsoluteUri "is NOT older than 1 days. KEEPING it."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment