loops - Powershell Remove Oldest Items -


i trying use while loop remove old files in multiple directories (starting oldest) until there 1 left, @ point program should end. program should run if there more 1 file in directory @ runtime.

here environment:

  • top folder
    • folder 1
    • folder 2
    • etc

in folder 1, folder 2, etc there should 1 file. script should delete latest , nothing @ if there 1 file in there begin with.

i have semi-accomplished using following code:

$basedir = "c:\test" set-location -path c:\test  $a = get-childitem -recurse $basedir  if ($a.count -gt 1) {          {         $a | sort-object lastwritetime -descending | select-object -last 1 | remove-item     }     while     (         $a.count -gt 1     ) }   
  1. it run when there more 1 file present, correct.
  2. it correctly deletes oldest file, keeps on trying delete same file rather rechecking directory.
  3. all need @ point getting re-run loop once has deleted file, rather trying delete same file on , over.

thank you, sincerely, , apologise if has been answered before. did lot of searching couldn't find situation.

brad

to fix yours, should re-define $a every time pass through loop, or avoid using $a altogether. $a doesn't change because child items there when created object have.

another way select last n-1 items in folder.

#get items aren't folders $items = get-childitems "c:\test" | ? {!($_.psiscontainer)} #get count - easier in posh 3 $itemcount = ($items | measure-object).count  if ($itemcount -gt 1){    $items | sort-object lastwritetime -descending | select-object -last ($itemcount - 1) | remove-item } 

to recursively easy. first of folders we'll need work in, we'll move code above foreach loop:

$folders = get-childitems "c:\test" -recurse | ? {$_.psiscontainer}  foreach ($folder in $folders) {     #get items aren't folders    $items = get-childitems $folder.fullname | ? {!($_.psiscontainer)}    #get count - easier in posh 3    $itemcount = ($items | measure-object).count     if ($itemcount -gt 1){       $items | sort-object lastwritetime -descending | select-object -last ($itemcount - 1) | remove-item    }  } 

you might need run both scripts prune root well, or add $folders += get-item "c:\test" before foreach loop


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -