We had a similar situation as described by @divineops in the question, but we wanted to create a new virtual directory each time we built a new version of the application (Angular + asp.net web api) so that multiple versions of the applications are available for testing, each sitting inside it own versioned virtual directory.
So, we needed the powershell script to create the virtual directory each time the release pipeline in devops ran.
On setting up the script provided by @iain-ward, we first encountered an error in Azure DevOps release pipeline where it told us to run the Login-AzureRmAccount command.
On running this command with the necessary parameters (i.e. the credentials), we got the next error as:
Method 'get_SerializationSettings' in type 'Microsoft.Azure.Management.WebSites.WebSiteManagementClient' from assembly 'Microsoft.Azure.Management.Websites, Version=1.0.0.2, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
To get past this error, I finally converted all the AzureRm commands to Az commands and below is the script that finally worked for me to accomplish this task of creation of a virtual directory from within a devops release pipeline:
$UserName = "<email>"
$Password = ConvertTo-SecureString "<password>" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
Login-AzAccount -Credential $Credential -SubscriptionName "<subscriptionName>" -TenantId "<tenantGuid>"
$website = Get-AzWebApp -Name "<appServiceName>" -ResourceGroupName "<resourceName>"
$VDApp = New-Object Microsoft.Azure.Management.WebSites.Models.VirtualApplication
$VDApp.VirtualPath = "/<virtualDirectory>"
$VDApp.PhysicalPath = "site\\wwwroot\\<physicalPath>"
$VDApp.PreloadEnabled ="NO"
$website.siteconfig.VirtualApplications.Add($VDApp)
$website | Set-AzWebApp
All items in "<>" are placeholders that you need to replace with values that pertain to your account.
Note - I had to specify the tenant id and the subscription id because my account was associated with multiples and the script was not able to choose which one to set as the current for the current script session.
Reference - It was based on this article that I decided to map all the AzureRm commands to Az commands as AzureRm is now outdated.