【问题标题】:Backing up folder using Powershell Copy-Item cmdlet使用 Powershell Copy-Item cmdlet 备份文件夹
【发布时间】:2015-05-06 23:05:03
【问题描述】:

我想备份过去 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"

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

我可以得到一些帮助吗?

【问题讨论】:

    标签: file powershell backup copy-item


    【解决方案1】:
    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))
        }
    }
    

    【讨论】:

    • 我曾想过单独创建文件夹结构但我不知道如何。感谢您的帮助。
    • 它告诉我第二个路径有问题: Copy-Item $storage -destination $thisbackup -recurse -container 它说 $thisbackup 不能是 unc 路径或驱动器,但它实际上是一个文件夹在备份驱动器中。
    • 嗨,保罗,下次我可以试试。我之前在使用 robocopy 时遇到了困难,因为它没有保留文件夹结构。这应该工作得很好。感谢您的帮助。
    猜你喜欢
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2018-06-06
    • 2013-08-01
    • 2020-11-04
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多