İçeriğe geç

PowerShell ile File Server ‘da Dosya Silme, Oluşturma ve Değiştirme Takibi

Bu yazıda, PowerShell kullanarak belirlediğimiz klasörlerde gerçekleşen dosya işlemlerini (silme, oluşturma, güncelleme) takip edecek ve bu bilgileri hem log dosyasına yazan hem de gün sonunda HTML formatında e-posta raporu gönderen bir script geliştireceğiz.
Ayrıca, silme olaylarında anlık e-posta bildirimi de göndereceğiz.

# === SMTP Ayarları ===
$smtpServer = "smtpmserver.com"
$smtpFrom   = "gönderici"
$smtpTo     = "gönderilecek kişi"
$smtpUser   = "smtp kullanıcı"
$smtpPass   = "parola"
$smtpPort   = port
$useSSL     = $true

# === İzlenecek klasörler ===
$foldersToWatch = @("D:\")

# === Log dosyası ===
$logFolder = "C:\Temp"
if (-not (Test-Path $logFolder)) { New-Item -ItemType Directory -Path $logFolder }
$logFile = Join-Path $logFolder "FileEvents.log"
if (-not (Test-Path $logFile)) { New-Item -ItemType File -Path $logFile }

# --- FileSystemWatcher oluştur ---
$watchers = @()
foreach ($folder in $foldersToWatch) {
    $fsw = New-Object System.IO.FileSystemWatcher
    $fsw.Path = $folder
    $fsw.IncludeSubdirectories = $true
    $fsw.EnableRaisingEvents = $true
    $fsw.NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite, CreationTime'
    $watchers += $fsw
}

# --- Olayları yakala ve logla ---
foreach ($fsw in $watchers) {
    Register-ObjectEvent $fsw Created -Action {
        $path = $Event.SourceEventArgs.FullPath
        $user = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
        Add-Content -Path $logFile -Value "$(Get-Date)|Created|$user|$path"
    }
    Register-ObjectEvent $fsw Changed -Action {
        $path = $Event.SourceEventArgs.FullPath
        $user = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
        Add-Content -Path $logFile -Value "$(Get-Date)|Modified|$user|$path"
    }
    Register-ObjectEvent $fsw Deleted -Action {
        $path = $Event.SourceEventArgs.FullPath
        $user = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
        Add-Content -Path $logFile -Value "$(Get-Date)|Deleted|$user|$path"

        # Silme anlık mail
        $htmlBody = @"
<html>
<head>
<style>
table {border-collapse: collapse; width: 100%;}
th, td {border: 1px solid black; padding: 8px; text-align: left;}
th {background-color: #ff4c4c; color: white;}
</style>
</head>
<body>
<h2>Dosya Silme Bildirimi</h2>
<table>
<tr><th>Tarih</th><th>Kullanıcı</th><th>Dosya/Klasör</th></tr>
<tr><td>$(Get-Date)</td><td>$user</td><td>$path</td></tr>
</table>
</body>
</html>
"@

        Send-MailMessage -From $smtpFrom -To $smtpTo -Subject "Dosya Silindi: $path" `
            -Body $htmlBody -BodyAsHtml -SmtpServer $smtpServer -Port $smtpPort -UseSsl:$useSSL `
            -Credential (New-Object PSCredential($smtpUser,(ConvertTo-SecureString $smtpPass -AsPlainText -Force)))
    }
}

# --- Gün sonu raporu ---
while ($true) {
    $now = Get-Date
    if ($now.Hour -eq 23 -and $now.Minute -eq 59 -and (Test-Path $logFile)) {
        $lines = Get-Content $logFile
        $events = @()

        foreach ($line in $lines) {
            $parts = $line -split '\|'
            $time = $parts[0]
            $eventType = $parts[1]
            $userName = $parts[2]
            $path = $parts[3]

            $color = switch ($eventType) {
                "Deleted"  { "red" }
                "Modified" { "orange" }
                "Created"  { "green" }
                default    { "black" }
            }

            $events += "<tr style='color:$color'><td>$time</td><td>$userName</td><td>$eventType</td><td>$path</td></tr>"
        }

        $htmlHeader = @"
<html>
<head>
<style>
table {border-collapse: collapse; width: 100%;}
th, td {border: 1px solid black; padding: 8px; text-align: left;}
th {background-color: #4CAF50; color: white;}
</style>
</head>
<body>
<h2>Günlük Dosya İşlem Raporu (Detaylı)</h2>
<table>
<tr><th>Tarih</th><th>Kullanıcı</th><th>EventType</th><th>Dosya/Klasör</th></tr>
"@
        $htmlFooter = @"
</table>
</body>
</html>
"@

        $fullHtml = $htmlHeader + ($events -join "`n") + $htmlFooter

        Send-MailMessage -From $smtpFrom -To $smtpTo -Subject "Günlük Dosya İşlem Raporu (Detaylı)" `
            -Body $fullHtml -BodyAsHtml -SmtpServer $smtpServer -Port $smtpPort -UseSsl:$useSSL `
            -Credential (New-Object PSCredential($smtpUser,(ConvertTo-SecureString $smtpPass -AsPlainText -Force)))

        Clear-Content $logFile
        Start-Sleep -Seconds 60
    }

    Start-Sleep -Seconds 10
}
Kategori:PowerShell

İlk Yorumu Siz Yapın

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir