param(
[Parameter(Mandatory=$false)]
[string]$Path = ".",
[Parameter(Mandatory=$false)]
[string]$Filter = "*",
[Parameter(Mandatory=$false)]
[switch]$IncludeSubdirectories,
[Parameter(Mandatory=$false)]
[string]$LogFile = "$env:TEMP\DirectoryMonitor.log"
)
# Prüfen ob Pfad existiert
if (-not (Test-Path -Path $Path)) {
Write-Error "Pfad '$Path' existiert nicht."
exit 1
}
# FileSystemWatcher anlegen
$watcher = New-Object System.IO.FileSystemWatcher -ArgumentList $Path, $Filter
$watcher.IncludeSubdirectories = $IncludeSubdirectories.IsPresent
$watcher.EnableRaisingEvents = $true
# Hilfs-Action für Created/Changed/Deleted
$commonAction = {
$time = Get-Date -Format "s"
$changeType = $Event.SourceEventArgs.ChangeType
$fullPath = $Event.SourceEventArgs.FullPath
$msg = "$time`t$changeType`t$fullPath"
Write-Host $msg
if ($using:LogFile) {
$msg | Out-File -FilePath $using:LogFile -Append -Encoding UTF8
}
}
# Separate Action für Renamed (enthält alte und neue Pfade)
$renamedAction = {
$time = Get-Date -Format "s"
$r = $Event.SourceEventArgs
$msg = "$time`tRenamed`t$($r.OldFullPath) -> $($r.FullPath)"
Write-Host $msg
if ($using:LogFile) {
$msg | Out-File -FilePath $using:LogFile -Append -Encoding UTF8
}
}
# Events registrieren und Referenzen sammeln
$subs = @()
$subs += Register-ObjectEvent -InputObject $watcher -EventName Created -SourceIdentifier FileCreated -Action $commonAction
$subs += Register-ObjectEvent -InputObject $watcher -EventName Changed -SourceIdentifier FileChanged -Action $commonAction
$subs += Register-ObjectEvent -InputObject $watcher -EventName Deleted -SourceIdentifier FileDeleted -Action $commonAction
$subs += Register-ObjectEvent -InputObject $watcher -EventName Renamed -SourceIdentifier FileRenamed -Action $renamedAction
Write-Host "Überwache '$Path' (Filter: '$Filter')" -ForegroundColor Green
if ($IncludeSubdirectories.IsPresent) { Write-Host " => Unterverzeichnisse eingeschlossen" }
Write-Host "Logfile: $LogFile"
Write-Host "Zum Beenden Strg+C drücken..."
try {
while ($true) { Start-Sleep -Seconds 1 } # Endlosschleife, damit Events verarbeitet werden
}
finally {
Write-Host "Beende Überwachung..." -ForegroundColor Yellow
foreach ($s in $subs) {
Unregister-Event -SubscriptionId $s.SubscriptionId -Force -ErrorAction SilentlyContinue
}
$watcher.EnableRaisingEvents = $false
$watcher.Dispose()
Write-Host "Fertig."
}