Windows性能记录文件默认存于C:\PerfLogs\,格式为.blg/.csv/.etl;可用logman query -ets和Get-ChildItem扫描定位;清理脚本按30天阈值删除非占用文件,并支持计划任务与日志审计。
确认性能记录文件的存放位置和格式
Windows 性能记录(如通过 Performance Monitor 或 logman 创建的 .blg、.csv、.etl 文件)通常保存在自定义路径,常见位置包括:
- C:\PerfLogs\(默认日志目录)
- 用户指定路径,例如 D:\Logs\PerfMon\
- 某些第三方监控工具可能使用子目录或带时间戳的命名规则(如 Server01_20250412_1430.blg)
建议先运行以下命令定位真实路径:
-
logman query -ets— 查看当前启用的性能计数器日志 -
Get-ChildItem "C:\PerfLogs" -Recurse -Include "*.blg","*.csv","*.etl" -ErrorAction SilentlyContinue— 扫描常见格式文件
编写删除脚本:按最后修改时间清理
以下脚本会删除指定目录下超过 30 天的性能记录文件(支持 .blg/.csv/.etl),并跳过正在被使用的文件(避免误删活跃日志):
param(
[string]$LogPath = "C:\PerfLogs",
[int]$DaysOld = 30
)
$limit = (Get-Date).AddDays(-$DaysOld)
Get-ChildItem -Path $LogPath -Recurse -Include "*.blg","*.csv","*.etl" -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt $limit -and (Test-Path $_.FullName -PathType Leaf) } |
ForEach-Object {
try {
Remove-Item $_.FullName -Force -ErrorAction Stop
Write-Host "已删除: $($_.FullName)" -ForegroundColor Green
}
catch {
Write-Warning "跳过 $($($_.FullName)): $($_.Exception.Message)"
}
}
保存为 Clean-PerfLogs.ps1,注意需在 PowerShell 中启用执行策略(如 Set-ExecutionPolicy RemoteSigned -Scope CurrentUser)。
添加到计划任务实现自动运行
用以下命令每天凌晨 2 点自动执行清理(管理员权限运行):
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\Scripts\Clean-PerfLogs.ps1`"" $trigger = New-ScheduledTaskTrigger -Daily -At "2:00AM" $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable $task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings Register-ScheduledTask "Clean-Performance-Logs" -TaskPath "\Custom\" -TaskName "Clean-Performance-Logs" -InputObject $task
也可通过“任务计划程序”图形界面导入,确保勾选“不管用户是否登录都要运行”和“不存储密码则只在用户登录时运行”(根据实际需求选择)。
安全增强与日志记录建议
生产环境建议增加简单审计能力:
- 在脚本开头添加日志写入:
$log = "C:\Scripts\Logs\perf_clean_$(Get-Date -Format 'yyyyMMdd').log"; "[$(Get-Date)] 开始清理" | Out-File $log -Append - 记录被删文件名:
"Deleted: $($_.FullName) ($($_.Length/1MB) MB)" | Out-File $log -Append - 避免误删:加
-WhatIf参数预览效果(测试阶段用),正式运行前移除 - 若日志由
logman start创建,建议先logman stop <name> -ets</name>再删除,防止句柄占用










