Author Posts

March 9, 2015 at 10:54 am

Dear Powershell Gurus,

I'm trying to write a script to copy files that are newer than 3-days old onto a backup drive. The copy is working in that it creates the files and folder in the target drive but it doesn't put the files in the target folders, it just leaves them in the main backup directory.

Get-ChildItem -recurse | where-object {$_.lastwritetime -gt (get-date).AddDays(-3)} | copy-item -destination h:\Backup\ -PassThru | Write-Output

So for example on my source directory c:\source (where I've changed-directory to before running the script)
c:\source\filea
c:\source\dira
c:\source\dira\fileb

In the target directory I see
h:\Backup\filea
h:\Backup\dira
h:\Backup\fileb <- fileb should be in h:\Backup\dira directory What am I doing wrong please? Thankyou kindly.

March 9, 2015 at 12:31 pm

Pop another -Recurse parameter into that Copy-Item statement to retain the file tree. You also might want to think about what to do if your script runs into a file that already exists. Overwrite? Keep both?

March 10, 2015 at 5:31 am

Hi Jack,

Thankyou for the suggestion. If I code -Recurse on the copy-item then it seems to ignore the list of files that were passed to the copy-item and just pull every file out of the directory, whether it was updated in the past 3 days or not. So, I'm still confused (I guess that's a common problem when at the bottom of the learning curve)

Any other ideas?

Thanks,

Jeff

March 10, 2015 at 12:04 pm

Woops, that's what I get for replying without testing. Give this a try.

$Source = "c:\somefolder"
$Replace = "c:\\somefolder"
$Destination = "h:\backup"
$CutoffDate = (Get-Date).AddDays(-3)

Get-ChildItem -Path $Source -Recurse | Where-Object { $_.LastAccessTime -gt $CutoffDate } | ForEach-Object {
    $Path = $_.FullName| Split-Path -Parent
    $NewPath = $Path -replace $Replace,$Destination
    Copy-Item -Path $_.FullName -Destination $NewPath -Force
}

March 11, 2015 at 10:19 am

Hi Jack,

That's helped. Thanks very much. I'm having trouble handing directories vs files but I'll find my way through that.

Thanks again.

Jeff