delete_files_with_specific_extensions.ps1
The snippet can be accessed without any authentication.
Authored by
Michael Urspringer
PS: Delete files with specific extensions
delete_files_with_specific_extensions.ps1 1.23 KiB
$rootPath = "C:\RootPath"
$logDirectory = "C:\LogPath"
$logFile = Join-Path $logDirectory "deleted_files_log.txt"
$dryRun = $true # Auf $false setzen, um tatsächlich zu löschen
# Zu löschende Endungen
$targetExtensions = @(".json", ".txt", ".ini")
# Logverzeichnis anlegen, falls nicht vorhanden
if (-not (Test-Path -Path $logDirectory)) {
New-Item -Path $logDirectory -ItemType Directory | Out-Null
}
# Logdatei vorbereiten
"--- Löschvorgang gestartet am $(Get-Date) --- (DryRun = $dryRun)`n" | Out-File -FilePath $logFile -Encoding UTF8
# Dateien prüfen
Get-ChildItem -Path $rootPath -Recurse -File | ForEach-Object {
$fileExtension = $_.Extension.ToLower()
if ($targetExtensions -contains $fileExtension) {
$message = if ($dryRun) {
"TEST: Würde löschen (zielgerichtet): $($_.FullName)"
} else {
"Lösche (zielgerichtet): $($_.FullName)"
}
Write-Host $message
$message | Out-File -FilePath $logFile -Append -Encoding UTF8
if (-not $dryRun) {
Remove-Item -Path $_.FullName -Force
}
}
}
"`n--- Löschvorgang abgeschlossen am $(Get-Date) ---`n" | Out-File -FilePath $logFile -Append -Encoding UTF8
Please register or sign in to comment