.net 如何使用webjob删除Azure Web应用程序的文件夹和文件

zbdgwd5y  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(133)

我们在我们的mvc web应用程序上有问题,为了克服这个问题,我们正在尝试删除文件夹并杀死Azure web应用程序的进程。为此,我们创建了一个控制台应用程序,它可以手动查询并杀死它,并编写powershell脚本来删除文件夹和文件,但在生产Azure Web应用程序上,我们有2个示例,因为powershell脚本只在一个示例上运行。我们如何使用Power Shell脚本或任何其他选项删除文件夹,我们必须删除文件。下面是杀死进程的代码:

using Microsoft.ApplicationInsights.Extensibility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace TestConsoleApp
{
   public class AzureWebAppProcessRecycle
   {
      static async Task Main(string[] args)
      {
        Console.WriteLine("Application restart started....");
        try
        {
            FormUrlEncodedContent tokenPayload = new FormUrlEncodedContent(new[]
                            {
                            new KeyValuePair<string, string>("client_id", ConfigurationManager.AppSettings["ClientId"]),
                            new KeyValuePair<string, string>("grant_type", "client_credentials"),
                            new KeyValuePair<string, string>("resource", ConfigurationManager.AppSettings["Resource"]),
                            new KeyValuePair<string, string>("client_secret", ConfigurationManager.AppSettings["ClientSecret"]),
                        });

            //Generate auth token
            HttpClient httpClient = new HttpClient();
            var tokenResponse = await httpClient.PostAsync($"{ConfigurationManager.AppSettings["AuthUrl"]}", tokenPayload);

            if (tokenResponse != null && tokenResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string jsonString = await tokenResponse.Content.ReadAsStringAsync();
                var tokenObject = JsonConvert.DeserializeObject<JObject>(jsonString);
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer", $"{tokenObject["access_token"]}");

                string listInstancesUrl = ConfigurationManager.AppSettings["ListInstancesUrl"];
                var instancesDetails = await httpClient.GetAsync(listInstancesUrl);
                if (instancesDetails != null)
                {
                    string jsonInstanceString = await instancesDetails.Content.ReadAsStringAsync();
                    var instancesListObj = JsonConvert.DeserializeObject<ProcessDetails>(jsonInstanceString);
                    if (instancesListObj != null && instancesListObj.value != null && instancesListObj.value.Count > 0)
                    {
                        foreach (var instance in instancesListObj.value)
                        {
                            string listProcessUrl = string.Format(ConfigurationManager.AppSettings["ListProcessUrl"], instance.name);
                            var processDtl = await httpClient.GetAsync(listProcessUrl);
                            if (processDtl != null)
                            {
                                string jsonProcessString = await processDtl.Content.ReadAsStringAsync();
                                var processListObj = JsonConvert.DeserializeObject<ProcessDetails>(jsonProcessString);
                                if (processListObj != null && processListObj.value != null && processListObj.value.Count > 0)
                                {
                                    foreach (var process in processListObj.value)
                                    {
                                        Console.WriteLine("Process : - " + JsonConvert.SerializeObject(process)); ;
                                        if (string.Equals(process.properties.name, "w3wp", StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            string processUrl = "https://management.azure.com" + process.id + "?api-version=2022-03-01";
                                            var getProDtl = await httpClient.GetAsync(processUrl);
                                            if (getProDtl != null)
                                            {
                                                string processPropsObj = await getProDtl.Content.ReadAsStringAsync();
                                                if (string.IsNullOrEmpty(processPropsObj) || (!string.IsNullOrEmpty(processPropsObj) && !processPropsObj.Contains("is_scm_site")))
                                                {
                                                    var processKillresp = await httpClient.DeleteAsync(processUrl);
                                                    if (processKillresp != null)
                                                    {
                                                        string killprocess = await processKillresp.Content.ReadAsStringAsync();
                                                        Console.WriteLine("Process kill details :- " + processPropsObj);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            else
            {
                string jsonString = await tokenResponse.Content.ReadAsStringAsync();
                Console.WriteLine("Failed to Connect service. Details are : " + jsonString);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to complete..." + ex.ToString());
        }
        Console.WriteLine("Application restart done....");
    }
  }
}

Power shell脚本如下:

try
{
    $CDrivefolderPath="C:\home\site\wwwroot\ImagesCollection"
    Get-ChildItem -Path $CDrivefolderPath -Include *.* -Recurse -EA 0 | ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue }
 }
 catch
 {}
 finally
 {
    .\TestConsoleApp.exe
 }

请帮助我从所有示例中删除此文件夹文件,而不是仅从一个示例中删除。
谢谢你,
桑迪

pod7payv

pod7payv1#

正如对@D A点的陈述一样,尝试重新部署应用程序或遵循以下方法。

  • 使用Azure Kudu API(Azure SCM或站点控制管理器),它是Azure Web Apps的高级管理平台。您可以与Kudu API交互,对所有示例执行操作。这是一个PowerShell脚本,用于使用Kudu API删除文件和文件夹。
# Specify your Azure Web App name and resource group
$webAppName = "YourWebAppName"
$resourceGroupName = "YourResourceGroupName"

# Specify the path of the folder you want to delete
$folderPath = "site\wwwroot\ImagesCollection"

# Get the list of all instances
$instances = (Get-AzureRmAppServicePlan -ResourceGroupName $resourceGroupName | Get-AzureRmWebApp -Name $webAppName).HostNames

foreach ($instance in $instances)
{
    # Construct the Kudu API URL for each instance
    $kuduUrl = "https://$webAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/$folderPath"

    # Authenticate to the Kudu API (use a deployment token)
    $kuduUserName = $webAppName
    $kuduPassword = "YourDeploymentToken" # Replace with your deployment token

    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $kuduUserName, $kuduPassword)))

    # Delete the folder and its contents
    $result = Invoke-RestMethod -Uri $kuduUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method DELETE
    Write-Host "Deleted folder on instance $instance."
}
  • 您可以使用Azure部署插槽来管理单独的环境。
  • 创建部署脚本或使用发布管理工具将脚本部署到每个示例。该脚本应部署到所有示例上的同一位置。
  • 要执行的PowerShell脚本(testade.ps1)存在于所有示例的指定路径中,并包含删除文件夹和文件的逻辑。

相关问题