Home > Software design >  How to upload and delete file of Azure web app using PowerShell
How to upload and delete file of Azure web app using PowerShell

Time:11-05

I am currently building an app service on Azure and want to write a PowerShell script to upload/delete files to the app service from the local side. I used Invoke-WebRequest to upload file and Invoke-RestMethod to delete file, but Catch [Exception] received a 405 message back. Do I need to perform identity verification for the Azure connection? How can I quickly implement it?

### init
$strHTTPS="https://xxx.azurewebsites.net/test/"   
$LocalFolder = "D:\AzureSolution\local_backup\"
$TargetFolder = $strHTTPS    "azure_backup/" 

#Connect to Azure app servuce
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$WebConnect = Invoke-WebRequest -URI $strHTTPS 
$WebContent = $WebConnect.Links | Select href

Foreach ($Item in $WebContent ) {
   $FileName = split-Path $Item.href -Leaf  

   #download file in local folder ---------------------------------> test OK
   $SourcefileName = $strHTTPS   $FileName
   $LocalFileName = $LocalFolder $FileName
   Try{
      Invoke-WebRequest -Uri $SourcefileName -OutFile $LocalFileName -PassThru 
   }
   Catch [Exception] {
      $ExceptionMsgPut = $_.Exception.GetType().FullName, $_.Exception.Message
   }

   #Backup file in Azure app servuce -------------------------------> test Failed
   $TargetFileName = $TargetFolder   $FileName
   $UploadWeb = New-Object System.Net.WebClient
   Try{
      $UploadWeb.UploadFile($TargetFileName,"PUT",$LocalFileName)
   }
   Catch [Exception] {
      $ExceptionMsgUpload = $_.Exception.GetType().FullName, $_.Exception.Message
   }         

   #Delete Azure Soruce File when completed ------------------------> test Failed
   Try{
      Invoke-RestMethod -Uri $SourcefileName -Method Delete 
   }
   Catch [Exception] {
      $ExceptionMsgDelete = $_.Exception.GetType().FullName, $_.Exception.Message
   }

   #Delete Local file when completed -------------------------------> test OK
   Try{
      Remove-Item $LocalFileName -recurse
   }
   Catch [Exception] {
      $ExceptionMsgDeleteLocalfile = $_.Exception.GetType().FullName, $_.Exception.Message
   }

}

[2021-11-05] Request Completed, use KUDU VFS API by @DeepDave-MT.

function Get-AzureRmWebAppPublishingCredentials($resourceGroupName, $webAppName){
    $resourceType = "Microsoft.Web/sites/config"
    $resourceName = "$webAppName/publishingcredentials"
    $publishingCredentials = Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType $resourceType -ResourceName $resourceName -Action list -ApiVersion 2015-08-01 -Force
    return $publishingCredentials
}

function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppName){
    $publishingCredentials = Get-AzureRmWebAppPublishingCredentials($resourceGroupName, $webAppName)
    return ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))
}

function Upload-FileToWebApp($resourceGroupName, $webAppName, $localPath, $kuduPath){
    $kuduApiAuthorisationToken = Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppName)
    $kuduApiUrl = "https://$webAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/$kuduPath"
    $virtualPath = $kuduApiUrl.Replace(".scm.azurewebsites.", ".azurewebsites.").Replace("/api/vfs/site/wwwroot", "")
    Write-Host " Uploading File to WebApp. Source: '$localPath'. Target: '$virtualPath'..."  -ForegroundColor DarkGray

    Invoke-RestMethod -Uri $kuduApiUrl `
                        -Headers @{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
                        -Method PUT `
                        -InFile $localPath `
                        -ContentType "multipart/form-data"
}

function Delete-FileToWebApp($resourceGroupName, $webAppName, $kuduPath){
    $kuduApiAuthorisationToken = Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppNamee)
    $kuduApiUrl = "https://$webAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/$kuduPath"
    $virtualPath = $kuduApiUrl.Replace(".scm.azurewebsites.", ".azurewebsites.").Replace("/api/vfs/site/wwwroot", "")
    Write-Host " Uploading File to WebApp. Source: '$localPath'. Target: '$virtualPath'..."  -ForegroundColor DarkGray

    Invoke-RestMethod -Uri $kuduApiUrl `
                    -Headers @{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
                    -Method DELETE
}

function Download-FileToWebApp($resourceGroupName, $webAppName, $kuduPath){
    $kuduApiAuthorisationToken = Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppNamee)
    $kuduApiUrl = "https://$webAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/$kuduPath"
    $virtualPath = $kuduApiUrl.Replace(".scm.azurewebsites.", ".azurewebsites.").Replace("/api/vfs/site/wwwroot", "")
    Write-Host " Uploading File to WebApp. Source: '$localPath'. Target: '$virtualPath'..."  -ForegroundColor DarkGray

    Invoke-RestMethod -Uri $kuduApiUrl `
                    -Headers @{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
                    -Method GET `
                    -OutFile $localPath `
                    -ContentType "multipart/form-data"

CodePudding user response:

You can use KUDU VFS API

PUT /api/zip/{path} (Upload a zip file which gets expanded into the specified folder)

DELETE /api/vfs/{path} (Delete the file at path)

You can refer to How can you delete files from an Azure WebApp using powershell?, Is it possible to delete a specific files in a directory of App Service in Powershell?? and Interacting with Azure Web Apps Virtual File System using PowerShell and the Kudu API

  • Related