1

I want to backup all files on a volume that have changed in the past 24 hours. I want the backup folder to keep the folder structure of the original. I find that when I test my current script, the folders are all placed in root.

$today = Get-Date -UFormat "%Y-%m-%d"

$storage="D:\"
$backups="E:\"
$thisbackup = $backups+$today

New-Item -ItemType Directory -Force -Path $thisbackup
foreach ($f in Get-ChildItem $storage -recurse)
{
    if ($f.LastWriteTime -lt ($(Get-Date).AddDays(-1)))
    {
        Copy-Item $f.FullName -Destination $thisbackup -Recurse
    }
}
Write-Host "The backup is complete"

It also seems to be copying ALL files in these folders.

Can I get some assistance on this?

1 Answer 1

2
if ($f.LastWriteTime -lt ($(Get-Date).AddDays(-1)))

should be

if ($f.LastWriteTime -gt ($(Get-Date).AddDays(-1)))

Your folders are all placed in the root because you are getting all items recursively via Get-Childitem.

The following should work:

#copy folder structure
robocopy $storage $thisbackup /e /xf *.*

foreach ($f in Get-ChildItem $storage -recurse -file)
{
    if ($f.LastWriteTime -gt ($(Get-Date).AddDays(-1)))
    {
    Copy-Item $f.FullName -Destination $thisbackup$($f.Fullname.Substring($storage.length))
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I had thought of separately creating the folder structure but I did not know how.Thanks for your help.
It's telling me there's a problem with the second path in: Copy-Item $storage -destination $thisbackup -recurse -container It says that $thisbackup cannot be a unc path or drive but it's actually a folder in the backup drive.
Hi Paul, will try next time I can. I had difficulty with robocopy before because it wasn't preserving the folder structure. This should work quite well. thanks for the assistance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.