You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选恢复名称以'dev'开头的已删除Azure AD应用(客户端证书认证)

筛选并恢复以"dev"开头的已删除Azure AD应用

步骤1:添加筛选条件

要筛选名称以"dev"开头的已删除应用,在获取请求中使用OData的startsWith函数匹配displayName字段前缀,在原代码的requestConfiguration中新增Filter参数即可:

requestConfiguration.QueryParameters.Filter = "startsWith(displayName, 'dev')";

步骤2:添加恢复逻辑

获取到符合条件的应用后,调用Microsoft Graph的恢复已删除目录对象接口,逐个恢复目标应用。注意恢复操作需要使用应用的目录对象ID(app.Id),而非应用ID(app.AppId)。

完整修改后的代码

using Azure.Identity;
using Microsoft.Graph;
using System.Security.Cryptography.X509Certificates;

var scopes = new[] { "https://graph.microsoft.com/.default" };
var clientId = "appID";
var tenantId = "tenantId";
var certificatePath = "C:/MYPATH";
var certificatePassword = "xxxxxxxx";
var clientCertificate = new X509Certificate2(certificatePath, certificatePassword);
var options = new ClientCertificateCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

var clientCertCredential = new ClientCertificateCredential(
    tenantId, clientId, clientCertificate, options);

var graphClient = new GraphServiceClient(clientCertCredential, scopes);

// 获取以"dev"开头的已删除应用
var devApps= await graphClient.Directory.DeletedItems.GraphApplication.GetAsync((requestConfiguration) =>
{
    requestConfiguration.QueryParameters.Count = true;
    requestConfiguration.QueryParameters.Orderby = new string[] { "deletedDateTime asc" };
    // 新增id字段,用于恢复操作
    requestConfiguration.QueryParameters.Select = new string[] { "id", "appId", "DisplayName", "deletedDateTime" };
    // 添加前缀筛选条件
    requestConfiguration.QueryParameters.Filter = "startsWith(displayName, 'dev')";
    requestConfiguration.Headers.Add("Consistencylevel", "Eventual");
});

Console.WriteLine($"符合条件的已删除dev应用总数: {devApps.OdataCount}\n");

if (devApps.Value != null && devApps.Value.Any())
{
    foreach (var app in devApps.Value)
    {
        Console.WriteLine($"正在恢复应用: {app.DisplayName} (App ID: {app.AppId})");
        try
        {
            // 执行恢复操作
            await graphClient.Directory.DeletedItems[app.Id].Restore.PostAsync();
            Console.WriteLine($"恢复成功\n");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"恢复失败: {ex.Message}\n");
        }
    }
}
else
{
    Console.WriteLine("未找到符合条件的已删除应用");
}

注意事项

  • 权限要求:应用注册必须添加Directory.ReadWrite.All应用权限并完成管理员同意,否则无法执行恢复操作。
  • 字段说明:修改Select参数新增id字段,是因为恢复接口依赖目录对象的唯一ID,而非应用的公开ID(AppId)。

内容的提问来源于stack exchange,提问作者user10563489

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:23:35