takvorian
Goto Top

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

#
# 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
**********************
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

Content-ID: 671850

Url: https://administrator.de/forum/loeschen-von-dateien-nach-alter-671850.html

Ausgedruckt am: 10.04.2025 um 01:04 Uhr

takvorian
takvorian 10.03.2025 um 15:18:30 Uhr
Goto Top
Lösungsansatz:

get-childitem $Source* -include $ext

ist evtl. der * hinter $Source falsch?

Tak
kpunkt
Lösung kpunkt 10.03.2025 aktualisiert um 15:39:46 Uhr
Goto Top
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.

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.
DerMaddin
DerMaddin 10.03.2025 um 15:37:26 Uhr
Goto Top
Moin,

wozu ein PS-Skript? Es gibt doch DelAge32|64
ThePinky777
ThePinky777 10.03.2025 um 18:40:15 Uhr
Goto Top
Powershell Script:

# 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.
DivideByZero
DivideByZero 10.03.2025 um 22:32:59 Uhr
Goto Top
+1 für DelAge, verrichtet klaglos und stabil seinen Job
Crusher79
Crusher79 11.03.2025 um 08:37:18 Uhr
Goto Top
Zitat von @DerMaddin:

Moin,

wozu ein PS-Skript? Es gibt doch DelAge32|64

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!
Crusher79
Crusher79 11.03.2025 um 08:40:32 Uhr
Goto Top
Get-ChildItem -Path '\\172.30.1.132\Allgemein' -Exclude '#recycle'  

Hab rasch mein Firmen Netzwerk gequält. Der Exclude oben sollte reichen!
takvorian
takvorian 22.03.2025 um 09:45:37 Uhr
Goto Top
Hallo zusammen,

danke für die Inputs. Ich hab das dank eurer Hilfe auch so hinbekommen wie ich es wollte.
Die Dokumente werden sauber gelöscht und auch mit den Papierkorb hab ich keine Probleme.

DelAge ist grundsätzlich eine super Sache, jedoch bekomme ich für das Tool keine Freigabe vom Infra/Netze Team.

VG Tak