如何使用 PowerShell 脚本备份和清理 Windows 事件日志 ?

42 阅读2分钟

PowerShell Script Backup and Cleanup Windows Event Logs

PowerShell 是一个强大的命令行工具,允许系统管理员可以自动执行许多日常任务,包括管理 Windows 事件日志。在这个脚本中,我们将创建一个 PowerShell 脚本将所有事件日志备份到指定位置,然后清除日志,以释放磁盘空间,提高系统性能。

设置 PowerShell 环境

在配置计划任务之前,请确保您的机器上安装了 PowerShell。

此外,您可能需要调整 PowerShell 的执行策略以允许脚本的执行。使用 administrative 权限打开 PowerShell 控制台,并执行如下命令:

Set-ExecutionPolicy RemoteSigned

这个命令允许执行本地创建的脚本和来自远程源的签名脚本。

Powershell: Set-ExecutionPolicy RemoteSigned

编写 PowerShell 脚本

下面是一个 PowerShell 脚本,它将 Windows 事件日志备份到日期格式文件夹,并删除备份后的旧事件。此脚本假定您在机器上拥有管理权限。

# Set variables
$backupFolderPath = "C:\EventLogBackup"
$currentDate = Get-Date
$backupPath = Join-Path -Path $backupFolderPath -ChildPath $currentDate.ToString("yyyy-MM-dd")
$logNames = @("Application", "System", "Security")
$daysToKeep = 30
 
# Create backup directory if it doesn't exist
if (!(Test-Path -Path $backupPath)) {
    New-Item -Path $backupPath -ItemType Directory | Out-Null
}
 
# Backup event logs and clear them
foreach ($logName in $logNames) {
    $exportFileName = "$logName-$($currentDate.ToString("yyyy-MM-dd")).evtx"
    $exportFilePath = Join-Path -Path $backupPath -ChildPath $exportFileName
 
    # Export the log
    Write-Host "Exporting $logName to $exportFilePath"
    wevtutil epl $logName $exportFilePath
 
    # Clear the log
    Write-Host "Clearing $logName event log"
    wevtutil cl $logName
}
 
# Remove backups older than the specified days
Get-ChildItem -Path $backupFolderPath -Directory | Where-Object {
    $folderDate = [datetime]::ParseExact($_.Name, "yyyy-MM-dd", $null)
    ($currentDate - $folderDate).Days -gt $daysToKeep
} | Remove-Item -Recurse -Force
 
# Script end

该脚本执行以下操作:

  • 设置要备份的事件日志的备份文件夹路径和名称。
  • 如果备份尚不存在,则创建以日期命名的文件夹。
  • 导出和清除指定的事件日志。
  • 删除超过指定天数的备份文件夹。

打开文本编辑器,粘贴以上内容,将脚本保存为 "BackupEventLogs.ps1",请确保调整 "backupFolderPath","logNames","daysToKeep" 变量以适应您的需求。

Execute PowerShell Script

(1) 打开 PowerShell 终端

(2) 在 PowerShell 终端,切换到脚本所在目录

cd C:\path\to\script\directory

(3) 执行脚本

.\BackupEventLogs.ps1

我的开源项目

酷瓜云课堂-在线教育解决方案