You dont have javascript enabled! Please enable it!

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync

6 Min. Read

In this article, we will show you how to mount a drive and persist an Azure File share connection with Windows, so even if you reboot your computer the connection is persisted.

Updated – 06/05/2019 – Global mapping support for Windows 10, version 1709, Windows 11, Windows Server 2019 and later

Introduction

Azure File storage offers shared storage for applications using the standard SMB 3.0 protocol. Microsoft Azure virtual machines and cloud services can share file data across application components via mounted shares, and on-premises applications can access file data in a share via the File storage API.

Applications running on Azure virtual machines can mount a File storage share to access file data, just as a desktop application would mount a typical SMB share. Any number of Azure virtual machines or roles can mount and access the File Storage share simultaneously.

Microsoft also introduced the Azure File Sync service which is a new service that will allow you to centralize your file shares in Azure Files, whilst maintaining the compatibility of an on-premises file server with all the flexibility and performance benefits provide. Any protocol installed on the Windows Server can access the Azure file share, including SMB, NFS, and FTPS. For more information about Azure File Sync and how to get started, please check the following step-by-step guide.

Since a File storage share is a standard SMB 3.0 file share, applications running in Azure can access data in the share via file I/O APIs. Developers can, therefore, leverage their existing code and skills to migrate existing applications. IT Professionals can use PowerShell cmdlets to create, mount, and manage File storage shares as part of the administration of Azure applications.

Mount and Persist an Azure file share with Windows

Now if you have been working with file shares for quite some time, you have probably come across a situation where you map a drive, and then reboot your computer to find out that the drive disappears…

If this is the case, please read on!

Store Azure storage account credentials

To get the mapped drive to persist, we should first store the Azure storage account key (credentials) using the cmdkey utility. Cmdkey is a utility that helps you to create, list, and delete stored usernames and passwords.

Open a normal PowerShell window (not as Administrator) and type the following command (make sure to change the storage account name, username, and password):

Invoke-Expression -Command "cmdkey /add:<storageaccountname>.file.core.windows.net /user:<storageaccountname> /pass:<storagekey>"

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 1

If you open Windows Credentials in Credential Manager, you can see that the credentials are stored now as persistence.

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 2

Mount Azure File Share Drive

Once the credentials are persisted, you can mount the drive now by specifying the Azure File Share full UNC path but without providing credentials. To do so, open a normal PowerShell window (not as Administrator) and type the following command:

New-PSDrive -Name Z -PSProvider FileSystem -Root "\\storageaccountname.file.core.windows.net\filesharename" -Persist

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 3

Now every time you reboot your machine, the mapped drive, in this case, Z drive is always persisted as shown in the following screenshot.

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 4

There’s more…

Please note that Windows Credentials are persisted in the same user context, in other words, if you logged in with a different user account on the same machine, you will notice that the credentials are not persisted. You need to follow the same steps as described above for every user who wants to use the UNC path after each login.

If you have an application that wants to access the UNC path in Azure files, what you can do, is set up the application with a deployment service to run as the (NT Authority\System) account instead of a user account. In this case, you need to download the PsExec tool from Microsoft, and then use the Cmdkey utility as described above to add the credentials. In this way, you can cache the credentials for the remote file share using the Windows Credential Manager.

To add the credentials when the target account is SYSTEM, you need to open a PowerShell session as Administrator, and then type the following commands (make sure to change the storage account name, file share name, username, and password):

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 5

.\PsExec.exe -s -accepteula -nobanner cmdkey /add:<storageaccountname>.file.core.windows.net /user:<storageaccountname> /pass:<storagekey>

.\PsExec.exe -s -accepteula -nobanner cmd.exe

Net use Z: "\\<storageaccountname>.file.core.windows.net\filesharename" /persistent:yes

Exit

How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync 6

Now every time you reboot your machine, your application will always have access to the file share using the (NT Authority\System) account instead of the user account.

Windows 10 1709 and Windows Server 2019

The steps described above are based on Windows Server 2016 or lower, including Windows 10 version 1703 or lower.

There are two caveats that you want to be aware of. In December 2018, Microsoft released an update (KB4469342) to address an important issue that causes mapped drives to fail to reconnect after starting and logging onto a Windows device. However, this fix still only applies to regular user accounts under the user context scenario as described above. It would have no effect on mapped drives created by service accounts such as SYSTEM or NetworkService. In other words, every time you reboot your machine, the SMB connection will not reconnect. If you want to persist a connection for file share under the SYSTEM or NetworkService account, you need to run a script at startup as described in this article.

The good news is, that starting with Windows 10 version 1709, Windows 11, Windows Server 2019, and above, you can use the new SMB Global mapping functionality to create a ‘global’ mapping that can be made accessible to the desired accounts.

To persist an SMB connection with Azure File Share under the SYSTEM account, you need to open a PowerShell session as Administrator, and then run the New-SMBGlobalMapping cmdlet as shown below (make sure to change the storage account name, file share name, username, and password):

$cred = Get-Credential
New-SmbGlobalMapping -RemotePath <storageaccountname>.file.core.windows.net `
 -Credential $cred -LocalPath Z: `
 -FullAccess @( "NT AUTHORITY\SYSTEM", "NT AUTHORITY\NetworkService" ) `
 -Persistent $true -RequirePrivacy $true

These mappings can be accessed by any account that satisfies the ACL constructed from the -FullAccess and -DenyAccess parameters. However, for lower versions of Windows, the Startup script is the best solution.

Mount Azure file share with Custom Script Extension

A recent user sent the following interesting question:

Did you try to mount an Azure file share with a Custom Script Extension in Azure IaaS VM? For example for an Azure Scale Set VM.

The short answer is yes! and here’s how to do it.

A quick overview about Custom Script Extension, it’s a tool that can be used to automatically launch and execute VM customization tasks post configuration. When this Extension is added to a Virtual Machine, it can download Powershell scripts and files from Azure Storage and launch a Powershell script on the VM which in turn can download additional software components. Custom Script Extension tasks can also be automated using the Azure Powershell cmdlets.

Follow the steps below to mount Azure file share with Custom Script Extension:

1) First, you need to create and save the following PowerShell script to a .PS1 file and upload it to one of your Azure storage accounts. Please note that the script file will be downloaded to the virtual machine and run. Do not use scripts with spaces in the file name. Replace the $storageAccountName, $fileShareName, and $storageAccountKeys variables with your own values.

The following script will leverage the storage account access keys, identity-based with domain-joined storage account to AD does not work with Custom Script Extension since it requires system context to run and not user context.

Please make sure to lock down your storage account from public access for added security.

# Mount Azure File Share with storage account access keys
function Get-TimeStamp {
    return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}
$storageAccountName = "storageaccountnamehere"
$fileShareName = "file-share-name-here"
$storageAccountKeys = "storage-account-access-keys-here"

$connectTestResult = Test-NetConnection -ComputerName $("$storageAccountName.file.core.windows.net") -Port 445

if ($connectTestResult.TcpTestSucceeded) {
    $password = ConvertTo-SecureString -String $storageAccountKeys -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential -ArgumentList "AZURE\$($storageAccountName)", $password
    New-PSDrive -Name Z -PSProvider FileSystem -Root "\\$($storageAccountName).file.core.windows.net\$($fileShareName)" -Credential $credential -Persist
    }
else {
    Write-Output "$(Get-TimeStamp) Unable to reach the Azure storage account via port 445. Please check your network connection." | Out-File C:\FileShareMount.txt -Append
}

2) Next, make sure to enable managed system identity on your Azure VM because you need to grant the identity of the VM with Storage Blob Data Contributor (RBAC role) as shown in the figure below to access the storage account where you uploaded the (.PS1) script above.

Add role assignment
Add role assignment

3) Lastly, you need to install the Custom Script Extension on the desired Azure VM and select the (.PS1) script from your Azure blob storage as shown in the figure below. Then click Review + create, and then Create.

Install Custom Script Extension
Install Custom Script Extension

You can of course automate the Custom Script Extension installation on Azure VM and Virtual Machine Scale Set (VMSS) using PowerShell, ARM Templates, or Bicep.

As soon as the Custom Script Extension is installed successfully, you can log in to the VM and see the file share is mounted under the system context as shown below.

Azure file share mounted with Custom Script Extension
Azure file share mounted with Custom Script Extension

That’s it there you have it!

Conclusion

It’s very important to follow the two steps described in this article because if you mount the drive first by specifying the credentials, and then store the storage account key, the drive won’t persist.

Azure Files and Azure File Sync give you the ability to share files without the need to deploy the underlying server infrastructure provides several benefits when building an Azure-based application.

Hope this helps!

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Photo of author
About the Author
Charbel Nemnom
Charbel Nemnom is a Senior Cloud Architect, Swiss Certified ICT Security Expert, Certified Cloud Security Professional (CCSP), Certified Information Security Manager (CISM), Microsoft Most Valuable Professional (MVP), and Microsoft Certified Trainer (MCT). He has over 20 years of broad IT experience serving on and guiding technical teams to optimize the performance of mission-critical enterprise systems with extensive practical knowledge of complex systems build, network design, business continuity, and cloud security.
Previous

(Solution) Azure File Sync – Server Endpoint Provisioning Failed – Error 2134376427

Holiday Giveaway From Vembu Technologies Before the End of the Year! @vembutech

Next

13 thoughts on “How to Mount and Persist an Azure File Share with Windows Easily #AzureFiles #AzureFileSync”

Leave a comment...

  1. When I try to mount such a Azure file share, I get an error:
    “New-PSDrive : The network resource type is not correct”

    If I remove “-Persist” then the operation will seemingly succeed, it will list the new drive with ‘Get-PSDrive’, If I want to create the same drive with New-PSDrive it will throw an error that it is already exists, yet, I the drive does not exist, I can’t change to it, and even ‘Test-Path Z’ says that the drive does not exist.

  2. What is the error that are you getting?
    Did you try to run the New-PSDrive under admin privilege.
    Or if you run it under user context, please try to add -Credential parameter “XXXXX\Admin”

    Thanks!

  3. Well it looks like your psexec examples do not work on Windows Server 2016 Datacenter.

    I ran an admin PowerShell.
    I run the cmdkey and it says “Credential added successfully.” but I go into Credential Manger and it’s not there. I run the net use command it says “The command completed successfully”. But File Explorer shows the mapping with “invalid credentials”. When I do a “cmdkey /list” the credentials aren’t there.
    I run a “whoami” and it shows I’m running as my not NT/System.

    I then tried running:
    .\PsExec.exe -s -accepteula -nobanner powershell
    Typeed “whoami” I get:
    nt authority\system

    Great I’m who I need to be.
    So I run the same psexec commands again and still nothing.

    Any thoughts?

  4. Nice write up Charbel!

    I see the credential in credential manager, but when I run the New-PSDrive with the -persist switch,

    New-PSDrive -Name Z -PSProvider FileSystem -Root “\\.file.core.windows.net\employee-information” -Persist

    I get the error: “New-PSDrive : The parameter is incorrect”

    Without the -Persist switch, it works but without mapping I can’t access via file explorer or share out to users

    I also tried to run:

    New-PSDrive -Name Z -PSProvider FileSystem -Root “\\.file.core.windows.net\employee-information” -Persist -Credential “Azure\sawallazfiles”

    After entering the key at the prompt, I still get the error: “New-PSDrive : The parameter is incorrect”

    Any idea what it could be or something else to try?

    Thanks for your help!

    Regards,
    Wes

  5. I had to disable NTLMv1 as well (besides disabling SMBv1 and enable SMBv2 which is the same stack as SMBv3) to get the Azure example working, and now it is fine.

  6. Did you try to mount an Azure file share but with a CustomScriptExtension? For example for an Azure Scale Set VM.

  7. Hi Charbel,

    Very good the content you made available.

    I’ve been trying to mount AFS in 2 azure server 2016, but I always get the following error:

    System error 1312 has occurred.
    A specified logon session does not exist. it may already have been terminated.

    I can see that I am the system and I have the credentials correctly configured with the cmdkey /list, but I cannot mount AFS with the system.

    However, if I perform the same procedure on a 2019 server, I can successfully do it.
    I checked the answer you informed Rick above about SMB1 but I have it disabled.

    Any other ideas of what it could be?

  8. Does anybody know if the New-SmbGlobalMapping drive mapping works similar to a local disk, i.e. if I reboot my Windows Server 2019 device and I don’t logon i.e. no user context will logon, will the system still be able to write to the SMB 3.x share?
    Also anybody tried to get this to work with MS Services? if so, can I run the service as local system and it will have access by default to the globally mapped share ?

    Thanks!

  9. Hello John, thanks for the comment!
    Yes, with the New-SmbGlobalMapping it works similar to a local disk, so if you reboot your Windows Server 2019 and don’t logon (no user context), you will still be able to write to the SMB 3.x share.
    This SMB global mapping support is SMB client-side feature which can work on top of any compatible SMB server including Azure Files (SMB share) and Traditional File Server, etc.
    As for your second question, yes you can do that and run the service as local system.
    For this to work, you need to open a PowerShell session as Administrator, and then run the New-SMBGlobalMapping cmdlet and give full access to ("NT AUTHORITY\SYSTEM", "NT AUTHORITY\NetworkService") as described in this section.
    Hope it helps!

Let me know what you think, or ask a question...

error: Alert: The content of this website is copyrighted from being plagiarized! You can copy from the 'Code Blocks' in 'Black' by selecting the Code. Thank You!