13
Function Move {
  #Moves all files older than 31 days old from the Source folder to the Target 
  Get-Childitem -Path "E:\source" | Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-31)} |
  ForEach {
    Move-Item $_.FullName -destination "F:\target" -force -ErrorAction:SilentlyContinue
  }
}

in the source directory are files that are older than 2-3 years, but when i run the script nothing moves to the target directory ?! whats wrong ?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
Maurizio Schmidt
  • 131
  • 1
  • 1
  • 3

2 Answers2

33

I don't know if this makes much of a difference, but rather than $. it needs to be $_.

I tried this script and it works fine for me:

get-childitem -Path "E:\source" |
    where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} | 
    move-item -destination "F:\target"

Notice you don't need a foreach loop because the objects will be "piped" into the move-item command

Matthew Steeples
  • 7,858
  • 4
  • 34
  • 49
  • get-currentitem you mean Get-Childitem ? – JPBlanc May 06 '11 at 14:39
  • why does it not work for me...very strange. i thought about the foreach to avoid problems, cause we have 20k+ files in some directorys.... – Maurizio Schmidt May 06 '11 at 15:13
  • @JPBlanc: Thanks very much, yes I do mean get-childitem. I'm used to writing gci. Have updated my post – Matthew Steeples May 07 '11 at 16:19
  • 1
    @Maurizio Schmidt: If you have files in subfolders this won't do it. You'll have to use the -Recurse flag on get-childitem, and additionally you'll have to work out how to move to the right folder on the destinations – Matthew Steeples May 07 '11 at 16:21
  • @ Matthew: Now it works perfectly, thx. i thought the foreach etc is necessary to avoid memory consumption problems caused by the fact that within some directorys we´ve more then 30.000 files. – Maurizio Schmidt May 09 '11 at 09:43
  • @Maurizio Schmidt: I don't know what the limits will be for memory, but if you've got too many files then I think you'll encounter the problem on the get-childitem method (as that will load them all up to begin with). – Matthew Steeples May 10 '11 at 15:51
4

Also be aware of hidden files, try adding -Force to Get-ChildItem

S.Spieker
  • 7,005
  • 8
  • 44
  • 50
Matias
  • 41
  • 1