Friday, July 14, 2023

Azure PowerShell: Check Directory Exists in Azure File Share

In this post, let's see how to check whether a Directory exists in Azure File Share using Azure PowerShell.

I am assuming you have connected to Azure with an authenticated account and have chosen the subscription in which your storage account resides by running the following commands.
Connect-AzAccount
Set-AzContext -Subscription "<SubscriptionId>"
Now first let's get a reference to the File Share.
$ResourceGroup = "<ResourceGroup>"
$StorageAccountName = "<StorageAccountName>"
$StorageFileShareName = "<StorageFileShareName>"

# Get Storage Account Key
$storageAccountKey = (Get-AzStorageAccountKey `
    -ResourceGroupName $ResourceGroup `
    -AccountName $StorageAccountName).Value[0]

# Set AzStorageContext
$storageContext = New-AzStorageContext `
    -StorageAccountName $StorageAccountName `
    -StorageAccountKey $storageAccountKey

# Get the FileShare
$storageFileShare = Get-AzStorageShare `
    -Name $StorageFileShareName `
    -Context $storageContext
Here Get-AzStorageShare cmdlet returns an AzureStorageFileShare. On that, we have this nice ShareClient property. And we can use that for basically all types of operations. In this case, we need to check whether a Directory exists, so we can do something like below.
if ($storageFileShare.ShareClient.GetRootDirectoryClient().GetSubdirectoryClient("parent-directory").Exists().Value)
{
    # Directory Exists
} else {
    # Directory does not exist
}
Here I am getting to the root of the File Share, getting to the directory of my choice, and checking whether it exists. You can even pass nested paths for the directoryName, something like "parent-directory/child-directory".

This is really neat.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment