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

如何编写PowerShell脚本清理绑定Log Analytics的Application Insight数据

Application Insight(绑定Log Analytics)日志清理操作指南

一、删除指定Application Insight日志的注意事项

你当前使用的Application Insight已启用Log Analytics功能,所有日志数据实际存储在绑定的Log Analytics工作区中,无法直接在Application Insight侧单独删除日志,需通过工作区的数据清除能力实现指定数据的删除,操作前需确认:

  • 日志删除为不可逆操作,执行前请确认无需保留对应数据或已完成数据备份
  • 操作账号需要持有Log Analytics工作区的数据清除者(Data Purger) 角色权限
  • 单次清除请求最多匹配100万条数据,若需要删除的数据量更大,需拆分时间范围分批次执行
  • 可删除的范围支持按时间区间、日志类型、自定义属性筛选,仅删除目标Application Insight产生的关联数据

二、清理关联工作区数据的PowerShell脚本

前置依赖

  • 已安装Azure Az PowerShell模块
  • 已执行Connect-AzAccount登录对应Azure租户,且已切换到目标订阅

完整脚本

# -------------------------- 配置参数替换区 --------------------------
# 替换为你的Azure订阅ID
$subscriptionId = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# 绑定的Log Analytics工作区所在资源组名称
$workspaceRgName = "your-workspace-resource-group"
# 绑定的Log Analytics工作区名称
$workspaceName = "your-log-analytics-workspace"
# 要清理数据的目标Application Insight名称
$targetAppInsightName = "your-application-insight"
# 要清理的时间范围(UTC时间)
$purgeStartTime = "2024-01-01T00:00:00Z"
$purgeEndTime = "2024-06-30T23:59:59Z"
# 要清理的Application Insight对应日志表,可按需增删
$targetTables = @(
    "AppRequests",
    "AppTraces", 
    "AppExceptions",
    "AppDependencies",
    "AppEvents",
    "AppMetrics"
)
# -------------------------------------------------------------------

# 切换到目标订阅
Set-AzContext -Subscription $subscriptionId | Out-Null

foreach ($table in $targetTables) {
    # 筛选规则:仅匹配目标Application Insight产生的指定时间范围内的日志
    $filter = "$table | where _ResourceId endswith '$targetAppInsightName' | where TimeGenerated between (datetime($purgeStartTime) .. datetime($purgeEndTime))"
    Write-Host "正在提交表[$table]的清除请求,筛选规则:$filter"
    
    # 提交清除任务
    $purgeTask = Invoke-AzOperationalInsightsPurge `
        -ResourceGroupName $workspaceRgName `
        -WorkspaceName $workspaceName `
        -Table $table `
        -Filter $filter
    
    Write-Host "表[$table]清除任务提交成功,任务ID:$($purgeTask.OperationId)`n"
}

补充操作说明

  • 清除任务为异步执行,提交后可运行以下命令查看任务执行状态:
    Get-AzOperationalInsightsPurgeStatus -ResourceGroupName $workspaceRgName -WorkspaceName $workspaceName -PurgeId <替换为返回的任务ID>
  • 若要删除对应Application Insight的全量日志,可移除$filter中的时间范围筛选条件
  • 若需删除特定场景的日志,可自行扩展$filter的筛选规则,比如追加| where SeverityLevel == 3仅删除错误级别的日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:06:04