Azure Runbook not deleting Files from File share

Adam Pool 1 Reputation point
2021-08-18T22:50:22.677+00:00

I am trying to setup an Azure Powershell Runbook to Delete Files from the Azure File share. When I run the Runbook there are no errors given, but the file is not deleted. I tested the code from the Powershell ISE on my desktop and it works fine. I have a run as account setup that is not expired and contributor permissions for it on the Storage Account.

Connect-AzAccount

$ctx = New-AzureStorageContext -StorageAccountName "" -StorageAccountKey ""
$shareName = ""
$directoryPath = ""
$DirIndex = 0
$day = 1
$startdate = (Get-Date).AddDays(-180)
$endDate = (Get-date).AddDays(-32)

$dirsToList = New-Object System.Collections.Generic.List[System.Object]

$shareroot = Get-AzureStorageFile -ShareName $shareName -Path $directoryPath -context $ctx
$dirsToList += $shareroot
While ($dirsToList.Count -gt $DirIndex)
{
$dir = $dirsToList[$DirIndex]
$DirIndex ++
$fileListItems = $dir | Get-AzureStorageFile
$dirsListOut = $fileListItems | where {$.GetType().Name -eq "AzureStorageFileDirectory"}
$dirsToList += $dirsListOut
$files = $fileListItems | where {$
.GetType().Name -eq "AzureStorageFile"}

 foreach($file in $files)
 {

     $task = $file.CloudFile.FetchAttributesAsync()
     $task.Wait()


        if ($file.CloudFile.Properties.LastModified -ge $startdate -and $file.CloudFile.Properties.LastModified -ge $endDate  )

     {
     if ($file.CloudFile.Properties.LastModified.day -ne '01'  )

        {
         $file | Remove-AzureStorageFile
         }
     }
        if ($file.CloudFile.Properties.LastModified -lt $startdate)

     {


         $file | Remove-AzureStorageFile 
     }

 }


 }
Azure Files
Azure Files
An Azure service that offers file shares in the cloud.
Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. tbgangav-MSFT 10,431 Reputation points Moderator
    2021-08-23T14:25:47.713+00:00

    Hi @Adam Pool ,

    I have made below mentioned changes to the script and it worked without any issues.

    1. Commented first line i.e., Connect-AzAccount which is not required in this case.
    2. Changed Azure cmdlets to recommended latest Az cmdlets i.e., used cmdlets of Az.Storage module. If you want to try out the updated script then before executing it as runbook in your Azure Automation account, make sure to successfully import Az.Storage module in your Azure Automation account.

    Here is the updated script for your reference.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.