window机器,自动日志清理powershell脚本

下面展示一些 内联代码片

# 设置要压缩的目录数组
$directories = @(
    "C:\path\to\first\directory",
    "D:\path\to\second\directory",
    "E:\path\to\third\directory"
    # 添加更多目录路径...
)
# 设置压缩文件保存的根目录路径
$destRootDir = "C:\archive-log"
# 设置要处理的文件的天数
$daysAgo = 7
# 获取当前日期和特定天数前的日期
$currentDate = Get-Date -Format yyyyMMdd
$targetDate =Get-Date ((Get-Date).AddDays(-$daysAgo)) -Format yyyyMMdd
# 设置 WinRAR 的路径
$winrarPath = "C:\Program Files\WinRAR\WinRAR.exe"
# 函数:计算字符串的哈希值
function Get-StringHash {
    param (
        [string]$InputString
    )
    $md5 = [System.Security.Cryptography.MD5]::Create()
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString)
    $hash = $md5.ComputeHash($bytes)
    return [BitConverter]::ToString($hash) -replace "-", ""
}
# 遍历目录数组
foreach ($sourceDir in $directories) {
    # 获取目录名称
    $dirName = Split-Path $sourceDir -Leaf
    # 计算目录路径的哈希值
    $pathHash = Get-StringHash $sourceDir
    # 设置压缩文件的目标路径(包括路径哈希值)
    $destDir = Join-Path $destRootDir "${dirName}_${pathHash}"
    # 设置压缩文件的名称(使用特定天数前的日期)
    $zipFileName = Join-Path $destDir "backup_$targetDate.zip"
    # 创建目标目录(如果不存在)
    if (-not (Test-Path $destDir)) {
        New-Item -ItemType Directory -Path $destDir | Out-Null
    }
    # 获取特定天数前的所有文件
    $filesToProcess = Get-ChildItem -Path $sourceDir -Recurse | Where-Object { $_.LastWriteTime -le (Get-Date).AddDays(-$daysAgo) }
    if ($filesToProcess.Count -eq 0) {
        Write-Host "没有找到需要处理的文件: $sourceDir"
        continue
    }
    # 创建一个临时目录用于存放要压缩的文件
    $tempDir = Join-Path $env:TEMP "TempCompression"
    if (Test-Path $tempDir) {
        Remove-Item $tempDir -Recurse -Force
    }
    New-Item -ItemType Directory -Path $tempDir | Out-Null
    # 复制要处理的文件到临时目录
    foreach ($file in $filesToProcess) {
        $destFilePath = Join-Path $tempDir (Split-Path -Leaf $file.FullName)
        Copy-Item -Path $file.FullName -Destination $destFilePath
    }
    # 使用 WinRAR 进行压缩
    try {
        & "$winrarPath" a -afzip "$zipFileName" "$tempDir\*"
        Write-Host "压缩成功: $zipFileName"
        # 等待5秒
        Start-Sleep -Seconds 5
        # 尝试删除特定天数前的源文件
        try {
            foreach ($file in $filesToProcess) {
                Remove-Item $file.FullName -Force
                Write-Host "已删除文件: $($file.FullName)"
            }
        } catch {
            Write-Error "删除文件失败: $sourceDir"
        }
    } catch {
        Write-Error "压缩失败: $sourceDir"
    } finally {
        # 清理临时目录
        Remove-Item $tempDir -Recurse -Force
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值