首页 > 解决方案 > 如何在备份脚本期间记录复制的项目?

问题描述

我需要制作基本/或更高级的备份脚本,将项目从文件夹 A 复制到文件夹 B,然后记录它所做的事情。

这可以很好地复制文件:

$source = 'path\gamybinis\*'
$dest = 'path\backup'

Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}| Copy-Item -Destination $dest -Recurse -Force

Write-Host "Backup started"
Pause

但在此之后我不能用 | 写日志 Out-File,所以我试过这个:

$source = 'path\gamybinis\*'
$dest = 'path\backup'
$logFile = 'path\log.txt'

$items = Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}

foreach($item in $items){
    Out-File -FilePath $logFile -Append
    Copy-Item -Path "$source\$item" -Destination $dest -Recurse -Force
}

Write-Host "Backup started"
Pause

这个完全没有做,我到底做错了什么?

(高级脚本部分是:备份最近修改的文件,然后将文件归档到 .rar/.zip,日志文件必须具有易于阅读的结构,并且日志文件应该包含备份期间用户在设备上工作的信息) - 对于那些想知道的人。

标签: powershell

解决方案


如果您不能使用 robocopy,则可以在纯 PowerShell 代码中执行此操作

$source  = 'path\gamybinis'  # no need for '\*' because you're specifying -Recurse
$dest    = 'path\backup'
$logFile = 'path\log.txt'

# test if the destination path exists. If not, create it first
if (!(Test-Path -Path $dest -PathType Container)) {
    $null = New-Item -Path $dest -ItemType Directory
}

Write-Host "Backup started"
Get-ChildItem -Path $source -Recurse | 
    Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } | 
    ForEach-Object {
        $_ | Copy-Item -Destination $dest -Recurse -Force
        Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
    }

Write-Host "Backup done"

从您的评论中,我了解到您在使用-Container开关时遇到了问题。
下面的代码不使用它并在备份文件夹中创建复制文件的文件夹结构,严格使用 Powershell 代码:

$source  = 'path\gamybinis'  # no need for '\*' because you're specifying -Recurse
$dest    = 'path\backup'
$logFile = 'path\log.txt'

Write-Host "Backup started"
Get-ChildItem -Path $source -File -Recurse | 
    Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } | 
    ForEach-Object {
        $target = Join-Path -Path $dest -ChildPath $_.DirectoryName.Substring($source.Length)
        if (!(Test-Path $target -PathType Container)) {
            # create the folder if it does not already exist
            $null = New-Item -Path $target -ItemType Directory
        }
        $_ | Copy-Item -Destination $target -Force
        Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
    }

Write-Host "Backup done"

推荐阅读