Azure PowerShell script for listing Azure File Share directories and files with creation date and last modified date

Niket Kumar Singh 190 Reputation points
2024-02-22T05:29:07.6233333+00:00

Hello community, I am working on a PowerShell script using the Azure PowerShell module to retrieve directories and files from an Azure File Share. The script is currently listing directories and files along with their sizes, but I am facing challenges in obtaining the creation date and last modified date for each directory and file.

Here is a snippet of my current script:

Install the Export-Excel module if not already installed

Install-Module -Name ImportExcel -Force -AllowClobber

Input Parameters

$resourceGroupName = "
$storageAccName = ""
$fileShareName = ""
$directoryPath = ""

Specify the customer's tenant ID

$customerTenantId = ""

Azure login to the customer's tenant

Connect-AzAccount -Tenant $customerTenantId

Set the default subscription

Set-AzContext -SubscriptionId ""

Import the Export-Excel module

Import-Module ImportExcel

Function to Lists directories and files along with their sizes in MB and exports to Excel

Function GetFiles {
    Write-Host -ForegroundColor Green "Listing directories and files with sizes in MB.."
    # Get the storage account context
    $ctx = (Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName).Context
    # Create an array to store file details
    $fileDetails = @()
    # List directories
    $directories = Get-AZStorageFile -Context $ctx -ShareName $fileShareName
    # Loop through directories
    foreach ($directory in $directories) {
        Write-Host -ForegroundColor Magenta "Directory Name: $($directory.Name)"
        # Add directory details to the array
        $fileDetails += [PSCustomObject]@{
            DirectoryName = $directory.Name
            FileName = $null  # Placeholder for files
            Size_MB = $null   # Placeholder for file size in MB
        }
        # List files in the current directory
        $files = Get-AZStorageFile -Context $ctx -ShareName $fileShareName -Path $directory.Name | Get-AZStorageFile
        # Loop through files
        foreach ($file in $files) {
            # Convert size to MB
            $sizeInMB = [math]::Round($file.Length / 1MB, 2)
            # Add file details to the array
            $fileDetails += [PSCustomObject]@{
                DirectoryName = $directory.Name
                FileName = $file.Name
                Size_MB = $sizeInMB
            }
        }
    }
    # Get the current date in the specified format
    $currentDateTime = Get-Date -Format "yyyyMMdd_HHmmss"
    # Specify the new export path with file share name and current date with time as the suffix
    $exportPath = "C:\Users\Niket kumar Singh\Downloads\lnt$fileShareName_$currentDateTime.xlsx"
    # Export to Excel
    $fileDetails | Export-Excel -Path $exportPath -AutoSize -Show
    Write-Host "Excel exported to: $exportPath"
}

Call the function

GetFiles

the above works fine while exporting the directory and file along with file size.

but when i modify the script to get the properties it not working and export is happeing but the workbook are empty.

Install the Export-Excel module if not already installed

Install-Module -Name ImportExcel -Force -AllowClobber  

Input Parameters

$resourceGroupName = ""
$storageAccName = ""
$fileShareName = ""
$directoryPath = "Presentation"
$customerTenantId = ""  

Azure login to the customer's tenant

Connect-AzAccount -Tenant $customerTenantId  

Set the default subscription

Set-AzContext -SubscriptionId ""  

Import the Export-Excel module

Import-Module ImportExcel  

Function to Lists directories and files along with their sizes, creation date, and last modified date, and exports to Excel

Function GetFiles {
    Write-Host -ForegroundColor Green "Listing directories and files with sizes, creation date, and last modified date in MB.."       # Get the storage account context
    $ctx = (Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName).Context       # Create an array to store file details
    $fileDetails = @()       # List directories
    $directories = Get-AZStorageFile -Context $ctx -ShareName $fileShareName       # Loop through directories
    foreach ($directory in $directories) {
        Write-Host -ForegroundColor Magenta "Processing Directory: $($directory.Name)"           # Output details for debugging
        $directory | Format-List           # Skip if directory URI is null
        if ($directory.Uri -eq $null) {
            Write-Host -ForegroundColor Yellow "Warning: Directory URI is null. Skipping Directory: $($directory.Name)"
            continue
        }           # HEAD request to get file properties
        try {
            $directoryProperties = Invoke-RestMethod -Method Head -Uri $directory.Uri -Headers @{
                "x-ms-version" = "2019-02-02"
                "Authorization" = "Bearer $($ctx.Token)"
            }
        }
        catch {
            Write-Host -ForegroundColor Red "Error retrieving directory properties. Directory Name: $($directory.Name)"
            Write-Host "Error details: $"
            continue
        }           # Add directory details to the array
        $directoryDetails = [PSCustomObject]@{
            DirectoryName = $directory.Name
            FileName = $null  # Placeholder for files
            Size_MB = $null   # Placeholder for file size in MB
            CreationDate = $directoryProperties.'x-ms-file-creation-time'  # Added creation date property
        }           $fileDetails += $directoryDetails           # List files in the current directory
        $files = Get-AZStorageFile -Context $ctx -ShareName $fileShareName -Path $directory.Name | Get-AZStorageFile           # Loop through files
        foreach ($file in $files) {
            Write-Host -ForegroundColor Cyan "Processing File: $($file.Name)"               # Output details for debugging
            $file | Format-List               # Skip if file URI is null
            if ($file.Uri -eq $null) {
                Write-Host -ForegroundColor Yellow "Warning: File URI is null. Skipping File: $($file.Name)"
                continue
            }               # HEAD request to get file properties
            try {
                $fileProperties = Invoke-RestMethod -Method Head -Uri $file.Uri -Headers @{
                    "x-ms-version" = "2019-02-02"
                    "Authorization" = "Bearer $($ctx.Token)"
                }
            }
            catch {
                Write-Host -ForegroundColor Red "Error retrieving file properties. File Name: $($file.Name)"
                Write-Host "Error details: $
"
                continue
            }               # Convert size to MB
            $sizeInMB = [math]::Round($file.Length / 1MB, 2)               # Add file details to the array
            $fileDetails += [PSCustomObject]@{
                DirectoryName = $directory.Name
                FileName = $file.Name
                Size_MB = $sizeInMB
                LastModified = $fileProperties.'x-ms-file-last-write-time'  # Added last modified date property
            }
        }
    }       # Get the current date in the specified format
    $currentDateTime = Get-Date -Format "yyyyMMdd_HHmmss"       # Specify the new export path with file share name and current date with time as the suffix
    $exportPath = "C:\Users\Niket kumar Singh\Downloads\lnt$fileShareName_$currentDateTime.xlsx"       # Export to Excel
    $fileDetails | Export-Excel -Path $exportPath -AutoSize -Show       Write-Host "Excel exported to: $exportPath"
}  

Call the function

GetFiles

result for this export :
User's image

I would appreciate your assistance in modifying the script to include the creation date and last modified date for both directories and files. Additionally, I intend to export this information to an Excel file. Thank you in advance for your help!

Azure Files
Azure Files
An Azure service that offers file shares in the cloud.
1,170 questions
Azure Storage Accounts
Azure Storage Accounts
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
2,716 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,082 questions
0 comments No comments
{count} votes

Accepted answer
  1. Amrinder Singh 2,195 Reputation points Microsoft Employee
    2024-02-22T17:54:35.23+00:00

    Hello @Niket Kumar Singh - Welcome to Microsoft Q&A Forum, thank you for posting your query here!

    From what I observed in the above snippet, you are able to get the Last Modified Date but not the Create Date. Can you please confirm if that is the issue being faced?

    When you call the cmdlet Get-AzStorageFile it returns the object of type AzureStorageFile. Therein we mainly get Last Modified time as the Property. There is also ListFileProperties Property which further has property associated with ShareFileItem. Herein, we could extract the CreatedOn details.

    I tried extracting details via below:

    Write-Host $directory.ListFileProperties.Properties.CreatedOn

    Suggest you to please try the same and let us know if you have any further queries. I’m happy to assist you further.

    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Niket Kumar Singh 190 Reputation points
    2024-02-22T19:15:55.4433333+00:00

    Thank you for your suppoort, it worked out.

    i have another script which calculate the fileshare size and its is not working: could you please look into this:

    Input Parameters

    $resourceGroupName = "" $storageAccName = "" $fileShareName = "" $directoryPath = ""

    Specify the customer's tenant ID

    $customerTenantId = ""

    Azure login to the customer's tenant

    Connect-AzAccount -Tenant $customerTenantId

    Set the default subscription

    Set-AzContext -SubscriptionId "" $fileinfo = @{ count = 0 length = 0 } function file_info() { $context = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName | Get-AzStorageAccountKey | %{ New-AzStorageContext -StorageAccountName $storageAccName -StorageAccountKey $_.Value } $shares = Get-AzStorageShare -Context $context foreach ($share in $shares) { # get all the files and directories in a file share $filesAndDirs = Get-AzStorageFile -ShareName $share.Name -Context $context foreach ($f in $filesAndDirs) { if ($f.gettype().name -eq "CloudFile") { Write-Output $f.Name $fileinfo["count"]++ $fileinfo["length"] = $fileinfo["length"] + $f.Properties.Length } elseif ($f.gettype().name -eq "CloudFileDirectory") { list_subdir $f -context $context } } } Write-Output "" Write-Output "File total count: " $fileinfo["count"] Write-Output "File total length: " $fileinfo["length"] " bytes" Write-Output "Used Capacity: " ([math]::Round($fileinfo["length"] / 1MB, 2)) " MB" } function list_subdir([Microsoft.WindowsAzure.Storage.File.CloudFileDirectory]$dirs, $context) { $path = $dirs.Uri.PathAndQuery.Remove(0, ($dirs.Uri.PathAndQuery.IndexOf('/', 1) + 1)) $filesAndDirs = Get-AzStorageFile -ShareName $dirs.share.Name -Path $path -Context $context | Get-AzStorageFile foreach ($f in $filesAndDirs) { if ($f.gettype().name -eq "CloudFile") { Write-Output $f.Name $fileinfo["count"]++ $fileinfo["length"] = $fileinfo["length"] + $f.Properties.Length } elseif ($f.gettype().name -eq "CloudFileDirectory") { list_subdir $f -context $context } } } file_info User's image

    REFERNCES : https://stackoverflow.com/questions/55728404/fast-way-to-check-azure-storage-account-file-share-used-capacity-with-powershell

    0 comments No comments

  2. Joseph Sundar Raj Paulraj 101 Reputation points
    2024-03-21T17:11:09.9066667+00:00

    This is good, but if you have any direct files under the share, those files will be considered as directory. using Where-Object {$_.GetType().Name -eq "AzureStorageFileDirectory"} while looping directories will be a good idea. But still size of those files which are directly into share will not get calculated.

    0 comments No comments