tags:

views:

26

answers:

1

I want to copy files that have timestamps from the time the script begins to run and a hour previous. So I am basically trying to emulate robocopy but with minage and maxage going down to the exact time rather than days. So far I have this in powershell:

$now = Get-Date
$previousHour = $now.AddHours(-1)
"Copying files from $previousHour to $now"

function DoCopy ($source, $destination)
{
 $fileList = gci $source -Recurse
 foreach ($file in $fileList)
 {
  if($file.LastWriteTime -lt $now -and $file.LastWriteTime -gt $previousHour)
  {
   #Do the copy
  }
 }
}

DoCopy "C:\test" "C:\test2"

but if I try to do the copy like that, it copies all the files directly into the destination folder rather than the subfolders.enter code here

+1  A: 

You will have to generate the entire destination path for each file you copy. The simplest way to do this is to replace the source folder with the destination one. You can replace your copy command with:

copy $file $file.FullName.Replace($source, $destination)

Note that you can replace the whole function with this one-liner:

gci $source -recurse | ?{$_.LastWriteTime -lt $now -and $_.LastWriteTime -gt $previousHour} | %{copy $_ $_.FullName.Replace($source, $destination)}

Some notes on the above:

  • ? is an alias of where-object, which filters the files you want to copy.
  • % is an alias of foreach. In this loop we copy each of the filtered files, replacing the source path name with the destination.
zdan