Keep x number of files and delete all others - Powershell -
Keep x number of files and delete all others - Powershell -
i trying write script through set of folders , maintain lastly 10 files. files in each folder created daily, weekly or monthly. need script maintain 10 recent copies regardless of creation date or modified date.
using post created script below works doesnt maintain 10 copies keeps file isn't older 10 days.
$ftppath = "c:\reports" get-childitem $ftppath -recurse *_report_*.zip -force|where {$_.lastwritetime -lt (get-date).adddays(-10)} |remove-item -force
any thought on how can tweak work? if utilize script below works if dont set -recurse. if utilize -recurse switch error have listed below script.
# keeps latest 10 files directory based on creation time #declaration variables $path = "c:\reports" # illustration $path= c:\log\*.tmp $total= (ls $path).count - 10 # alter number 5 whatever number of objects want maintain # script ls $path |sort-object -property {$_.creationtime} | select-object -first $total | remove-item -force
error: select-object : cannot validate argument on parameter 'first'. -7 argument less minimum allowed range of 0. supply argument greater 0 , seek command again.
updated
$path = "c:\testdir" # create 12 test files, 1 sec after each other 1..12 | % { remove-item -path "$path\$_.txt" -ea silentlycontinue $_ | out-file "$path\$_.txt" start-sleep -seconds 1 } $files = get-childitem -path $path -recurse | where-object {-not $_.psiscontainer} $keep = 10 if ($files.count -gt $keep) { $files | sort-object creationtime | select-object -first ($files.count - $keep) | remove-item -force -whatif }
remove -whatif
parameter remove-item
when ready delete real.
powershell powershell-v2.0
Comments
Post a Comment