如何使用 PowerShell 上传和删除 Azure Web 应用程序的文件

How to upload and delete file of Azure web app using PowerShell

我目前正在 Azure 上构建应用服务,并希望将 PowerShell 脚本写入 upload/delete 文件,从本地端传输到应用服务。我使用 Invoke-WebRequest 上传文件并使用 Invoke-RestMethod 删除文件,但是 Catch [Exception] 收到了一条 405 消息。我是否需要对 Azure 连接进行身份验证?如何快速实施?

### 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] 请求已完成,使用@DeepDave-MT 的KUDU VFS API

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"

您可以使用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)

可以参考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