Löschen von Dateien nach Alter
Hallo zusammen,
ich habe ein PowerShell Script welches mir Dateien aus einem freigegebenen Verzeichnis nach Dateiendung und Alter löscht
Soweit so gut. Nach ersten Tests und dem Logfile
Sieht für mich aus, als würde das Script die Dateien in den Papierkorb schieben wollen.
Kann mir hier jemand helfen, damit ich die Daten hart gelöscht bekomme?
Vielen Dank,
Gruß Tak
ich habe ein PowerShell Script welches mir Dateien aus einem freigegebenen Verzeichnis nach Dateiendung und Alter löscht
#
# Beschreibung:
# Dieses Skript löscht Dateien, die eine bestimmte Anzahl von Tagen alt sind. Die Dateierweiterungen, das Alter sowie der Ablageort sind definierbar.
# Der Löschvorgang erstreckt sich auf alle Unterordner
# Alle Operationen werden in einem Logfile im Quellordner gespeichert
#
# Hier können Sie den Quellordner, das Alter der Dateien (in Tagen) und die Dateierweiterungen festlegen
$Source = "\\synology-nas\share\" # Wichtig: muss mit "\" enden
$Days = 14 # Anzahl der Tage, nach denen die Dateien gelöscht werden
$ext = "*.pdf" # Array - erweitern mit ,".xyz"
$log = "$Source$(get-date -format yymmddHHmmss).txt"
$DateBeforeXDays = (Get-Date).AddDays(-$Days)
# Start Script
start-transcript $log
write-host "--------------------------------------------------------------------------------------"
write-host "Löschen aller Dateien ($ext) im Ordner $Source die älter sind als $Days Tage."
write-host "--------------------------------------------------------------------------------------"
get-childitem $Source* -include $ext -recurse | where {$_.lastwritetime -lt $DateBeforeXDays -and -not $_.psiscontainer} | remove-item -force -verbose
stop-transcript
Soweit so gut. Nach ersten Tests und dem Logfile
**********************
nStart der Windows PowerShell-Aufzeichnung
Startzeit: 20250310030002
Benutzername: xxx
RunAs-Benutzer: xxx
Konfigurationsname:
Computer: xxx(Microsoft Windows NT 10.0.20348.0)
Hostanwendung: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command C:\xxx\xxx.ps1
Prozess-ID: 2444
PSVersion: 5.1.20348.2582
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.20348.2582
BuildVersion: 10.0.20348.2582
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Die Aufzeichnung wurde gestartet. Die Ausgabedatei ist "\\synology-nas\share\250010030002.txt".
--------------------------------------------------------------------------------------
Löschen aller Dateien (*.pdf *.txt) im Ordner \\synology-nas\share\ die älter sind als 14 Tage.
--------------------------------------------------------------------------------------
get-childitem : Unerwarteter Netzwerkfehler.
In C:\Bereinigung_xxx\xxx.ps1:19 Zeichen:1
+ get-childitem $Source* -include $ext -recurse | where {$_.lastwriteti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (\\synology-nas\share\#recycle:String) [Get-ChildItem], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
get-childitem : Unerwarteter Netzwerkfehler.
In C:\Bereinigung_xxx\xx.ps1:19 Zeichen:1
+ get-childitem $Source* -include $ext -recurse | where {$_.lastwriteti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (\\synology-nas\share\#recycle:String) [Get-ChildItem
], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
**********************
Ende der Windows PowerShell-Aufzeichnung
Endzeit: 20250310030037
**********************
Kann mir hier jemand helfen, damit ich die Daten hart gelöscht bekomme?
Vielen Dank,
Gruß Tak
Bitte markiere auch die Kommentare, die zur Lösung des Beitrags beigetragen haben
Content-ID: 671850
Url: https://administrator.de/forum/loeschen-von-dateien-nach-alter-671850.html
Ausgedruckt am: 10.04.2025 um 01:04 Uhr
8 Kommentare
Neuester Kommentar
Ich sage ja. Den Asterisk hast du ja schon über $ext. Mach da nur ein PDF draus und filtere mit dem Asterisk, dann sieht das ungefähr so aus.
PS: -Filter ist schneller als -Include. Ersteres filtert schon beim Ausführen, letzteres filtert erst nach dem Abruf der Elemente aus.
Get-ChildItem -Path $Source -Filter "*.$ext" -File -Recurse | where ...
PS: -Filter ist schneller als -Include. Ersteres filtert schon beim Ausführen, letzteres filtert erst nach dem Abruf der Elemente aus.
Powershell Script:
Und dann Zeilen wie:
Mit Fileendungen muss man dann selbst reinbauen, hab ich nie getestet.
# Function to remove all empty directories under the given path.
# If -DeletePathIfEmpty is provided the given Path directory will also be deleted if it is empty.
# If -OnlyDeleteDirectoriesCreatedBeforeDate is provided, empty folders will only be deleted if they were created before the given date.
# If -OnlyDeleteDirectoriesNotModifiedAfterDate is provided, empty folders will only be deleted if they have not been written to after the given date.
function Remove-EmptyDirectories([parameter(Mandatory)][ValidateScript({Test-Path $_})][string] $Path, [switch] $DeletePathIfEmpty, [DateTime] $OnlyDeleteDirectoriesCreatedBeforeDate = [DateTime]::MaxValue, [DateTime] $OnlyDeleteDirectoriesNotModifiedAfterDate = [DateTime]::MaxValue, [switch] $OutputDeletedPaths, [switch] $WhatIf)
{
Get-ChildItem -Path $Path -Recurse -Force -Directory | Where-Object { (Get-ChildItem -Path $_.FullName -Recurse -Force -File) -eq $null } |
Where-Object { $_.CreationTime -lt $OnlyDeleteDirectoriesCreatedBeforeDate -and $_.LastWriteTime -lt $OnlyDeleteDirectoriesNotModifiedAfterDate } |
ForEach-Object { if ($OutputDeletedPaths) { Write-Output $_.FullName } Remove-Item -recurse -Path $_.FullName -Confirm:$false -Force -WhatIf:$WhatIf }
# If we should delete the given path when it is empty, and it is a directory, and it is empty, and it meets the date requirements, then delete it.
if ($DeletePathIfEmpty -and (Test-Path -Path $Path -PathType Container) -and (Get-ChildItem -Path $Path -Force) -eq $null -and
((Get-Item $Path).CreationTime -lt $OnlyDeleteDirectoriesCreatedBeforeDate) -and ((Get-Item $Path).LastWriteTime -lt $OnlyDeleteDirectoriesNotModifiedAfterDate))
{ if ($OutputDeletedPaths) { Write-Output $Path } Remove-Item -recurse -Path $Path -Confirm:$false -Force -WhatIf:$WhatIf }
}
# Function to remove all files in the given Path that were created before the given date, as well as any empty directories that may be left behind.
function Remove-FilesCreatedBeforeDate([parameter(Mandatory)][ValidateScript({Test-Path $_})][string] $Path, [parameter(Mandatory)][DateTime] $DateTime, [switch] $DeletePathIfEmpty, [switch] $OutputDeletedPaths, [switch] $WhatIf)
{
Get-ChildItem -Path $Path -Recurse -Force -File | Where-Object { $_.CreationTime -lt $DateTime } |
ForEach-Object { if ($OutputDeletedPaths) { Write-Output $_.FullName } Remove-Item -recurse -Path $_.FullName -Confirm:$false -Force -WhatIf:$WhatIf }
Remove-EmptyDirectories -Path $Path -DeletePathIfEmpty:$DeletePathIfEmpty -OnlyDeleteDirectoriesCreatedBeforeDate $DateTime -OutputDeletedPaths:$OutputDeletedPaths -WhatIf:$WhatIf
}
# Function to remove all files in the given Path that have not been modified after the given date, as well as any empty directories that may be left behind.
function Remove-FilesNotModifiedAfterDate([parameter(Mandatory)][ValidateScript({Test-Path $_})][string] $Path, [parameter(Mandatory)][DateTime] $DateTime, [switch] $DeletePathIfEmpty, [switch] $OutputDeletedPaths, [switch] $WhatIf)
{
Get-ChildItem -Path $Path -Recurse -Force -File | Where-Object { $_.LastWriteTime -lt $DateTime } |
ForEach-Object { if ($OutputDeletedPaths) { Write-Output $_.FullName } Remove-Item -recurse -Path $_.FullName -Confirm:$false -Force -WhatIf:$WhatIf }
Remove-EmptyDirectories -Path $Path -DeletePathIfEmpty:$DeletePathIfEmpty -OnlyDeleteDirectoriesNotModifiedAfterDate $DateTime -OutputDeletedPaths:$OutputDeletedPaths -WhatIf:$WhatIf
}
# Delete all files created more than 2 days ago.
# Remove-FilesCreatedBeforeDate -Path "C:\Some\Directory" -DateTime ((Get-Date).AddDays(-2)) -DeletePathIfEmpty
# Delete all files that have not been updated in 8 hours.
# Remove-FilesNotModifiedAfterDate -Path "C:\Another\Directory" -DateTime ((Get-Date).AddHours(-8))
# Delete a single file if it is more than 30 minutes old.
# Remove-FilesCreatedBeforeDate -Path "C:\Another\Directory\SomeFile.txt" -DateTime ((Get-Date).AddMinutes(-30))
# Delete all empty directories in the Temp folder, as well as the Temp folder itself if it is empty.
# Remove-EmptyDirectories -Path "C:\SomePath\Temp" -DeletePathIfEmpty
# Delete all empty directories created after Jan 1, 2014 3PM.
# Remove-EmptyDirectories -Path "C:\SomePath\WithEmpty\Directories" -OnlyDeleteDirectoriesCreatedBeforeDate ([DateTime]::Parse("Jan 1, 2014 15:00:00"))
# See what files and directories would be deleted if we ran the command.
# Remove-FilesCreatedBeforeDate -Path "C:\SomePath\Temp" -DateTime (Get-Date) -DeletePathIfEmpty -WhatIf
# Delete all files and directories in the Temp folder, as well as the Temp folder itself if it is empty, and output all paths that were deleted.
# Remove-FilesCreatedBeforeDate -Path "C:\SomePath\Temp" -DateTime (Get-Date) -DeletePathIfEmpty -OutputDeletedPaths
Und dann Zeilen wie:
Remove-FilesCreatedBeforeDate -Path "C:\TEMP" -DateTime ((Get-Date).AddDays(-30))
Remove-FilesCreatedBeforeDate -Path "D:\TEMP" -DateTime ((Get-Date).AddDays(-60)) -DeletePathIfEmpty
Mit Fileendungen muss man dann selbst reinbauen, hab ich nie getestet.
Kommt drauf an... Hab auch was auf Debian. Die Bash hat mir nicht gereicht. PowerShell 7 drauf und gut ist.
Get-ChildItem $localdir -Recurse | Where-Object { $_.LastWriteTime -lt $((Get-Date).AddDays(-21)) -and $_.LastWriteTime.Day -notin 1,15 } | Remove-Item -Force -Recurse
Der Syntax ist soweit klar. Hier wird noch der 1. und 15. stehen gelassen.
Die Fehlermeldung sieht komisch aus. Hasthtag bricht Syntax. so sieht es so aus, als wäre es ein Kommentar.
Ich würde mal den Papierkorb ausschließen. Pauschal sollte Get-ChildItem alles anzeigen, was uner Share liegt.
Where-Object Name -NotIn @('Windows','Program Files','$Recycle.Bin')
Bei dir wäre es nur der letzte Ordner. Ansonsten gibt doch nur aus, ohne zu löschen. Dann siehst du, ob der Befehl zu gierig war!