使用 Powershell Copy-Item cmdlet 备份文件夹

Backing up folder using Powershell Copy-Item cmdlet

我想备份过去 24 小时内更改过的卷上的所有文件。我想让备份文件夹保持原来的文件夹结构。我发现当我测试我当前的脚本时,文件夹都放在根目录下。

$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"

它似乎也在复制这些文件夹中的所有文件。

我可以得到一些帮助吗?

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

应该是

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

您的文件夹都放在根目录中,因为您通过 Get-Childitem 递归地获取所有项目。

以下应该有效:

#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))
    }
}