Backup copies files but doesn't put them in correct directory

Welcome Forums General PowerShell Q&A Backup copies files but doesn't put them in correct directory

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
3 years, 9 months ago.

  • Author
    Posts
  • #23155

    Participant
    Points: 1
    Rank: Member

    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.

  • #23160

    Participant
    Points: 0
    Rank: Member

    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?

  • #23181

    Participant
    Points: 1
    Rank: Member

    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

  • #23205

    Participant
    Points: 0
    Rank: Member

    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
    }
    
  • #23244

    Participant
    Points: 1
    Rank: Member

    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

The topic ‘Backup copies files but doesn't put them in correct directory’ is closed to new replies.