
目前,我每次寫入變更時都會自動備份交換器/路由器設定...這是透過 ftp 將文字檔案傳送到資料夾來完成的。
我正在嘗試編寫一個腳本來刪除目錄中超過 15 天的所有檔案。不過,我想保留每個設備的最新文件,即使它已經超過 15 天。
檔案命名的格式如下: 最新檔案名稱為 Hostname-Config-Change.txt,當被較新的變更覆蓋時,它會重新命名為: Hostname-Config-Change_MM-DD-YY_HH-MM-SS_Time.txt
我認為完成此操作的最簡單方法是刪除名稱中包含日期和時間且時間超過 15 天的所有檔案。我不知道如何解決這個問題,儘管我已經找到了執行其中任何一個的方法,但我還沒有找到同時執行這兩個操作的方法。
預先感謝您提供的任何幫助。
這是我到目前為止的程式碼。我現在使用 powershell,所以任何建議將不勝感激。
#Set Variables
# Get current date/time then subtract days to keep files.
$limit = (Get-Date).AddDays(-15)
#Set path of Files to be scanned & deleted
$path = "Directory to Files"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
#End of Script
答案1
只是為了方便每個可能關注的人使用。使用上面的回應,我能夠弄清楚如何使用正規表示式來查看檔案名稱中日期早於 X 天的任何檔案。最新文件的文件名中不包含日期,因此它對我有用。請注意,您必須根據日期的語法調整正規表示式。
#Set Variables
# Get current date/time then subtract days to keep files.
$limit = (Get-Date).AddDays(-15)
#Set path of Files to be scanned & deleted
$path = "D:\BACKUPS\ConfigChange"
# Delete files older than the $limit and matching the dates in the file name.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.BaseName -match '(\d{2})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})' -and $_.CreationTime -lt $limit } | Remove-Item -Force
#End of Script