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

时间:2015-05-06 23:05:04

标签: file powershell backup copy-item

我想备份过去24小时内已更改的卷上的所有文件。我希望备份文件夹保留原始文件夹的结构。我发现当我测试当前脚本时,文件夹全部放在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"

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

我可以就此获得一些帮助吗?

1 个答案:

答案 0 :(得分:2)

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))
    }
}
相关问题