从备份中替换小于 1KB 的文件

从备份中替换小于 1KB 的文件

我需要使用备份来替换共享文件夹中的损坏文件。所有损坏文件的大小都是固定的 = 1KB,并且设置了存档标志。基本上,只有当目标文件小于等于 1KB 和/或设置了存档标志时,我才会用备份中的文件替换目标文件夹中的文件。

Robocopy 看起来是一个可行的工具,但我看不到针对目标文件进行条件调整的选项。另一个看起来可以做到这一点的工具是 Powershell,但我对它不熟悉。

我如何使用这两个程序来实现这一点?

答案1

Powershell 解决方案,可以报告和/或恢复损坏的文件:

# Use full paths!
$Backup = '\\server\backup'
$Corrupted = 'c:\broken_folder'

# Path for log file, can be relative
$LogFile = '.\Restore.log'

# If this variable is set to true, no files will be copied
$ReportOnly = $true

# Remove log file, if exist
if(Test-Path -Path $LogFile -PathType Leaf)
{
    Remove-Item -Path $LogFile -Force
}

# Get all files in directory, recursive
$Corrupted | Get-ChildItem -Recurse |
    # Select files with archive attribute: $_.Mode -like '*a*'
    # And size less or equal to 1KB: ($_.Length / 1KB) -le 1 . Less fancy way: $_.Length -le 1024
    # Ignore folders: -not $_.PsIsContainer
    #
    # In PS 3.0 and higher Get-ChildItem has less cryptic way to get folders and specify attributes:
    # http://www.powershellmagazine.com/2012/08/27/pstip-how-to-get-only-files-the-powershell-3-0-way
    Where-Object {($_.Mode -like '*a*') -and (($_.Length / 1KB) -le 1) -and (-not $_.PsIsContainer)} |
        ForEach-Object {
            # Output log record to pipeline, Tee-Object will catch it later
            "Found corrupted file: $($_.FullName)"

            # Replace current file path with path fo this file in backup folder
            $NewFile =  $_.FullName -replace [regex]::Escape($Corrupted), $Backup

            if(Test-Path -Path $NewFile -PathType Leaf)
            {
                # Output log record to pipeline, Tee-Object will catch it later
                "Found corresponding file from backup: $NewFile"
            }
            else
            {
                # Output log record to pipeline, Tee-Object will catch it later
                "Failed to find corresponding file from backup: $NewFile"
                return
            }

            if(-not $ReportOnly)
            {
                # Output log record to pipeline, Tee-Object will catch it later
                "Restoring file from backup: $NewFile -> $($_.FullName)"

                # Remove corrupted file
                Remove-Item -Path $_.FullName -Force

                # Copy file from backup
                Copy-Item -Path $NewFile -Destination $_.FullName -Force
            }
        } | Tee-Object -FilePath $LogFile -Append # Send log to screen and file

答案2

Robocopy 具有您需要的参数。例如:

/A :: 仅复制具有存档属性集的文件。

/M :: 仅复制具有存档属性的文件并将其重置。


/MAX:n :: 最大文件大小 – 排除大于 n 字节的文件。

/MIN:n :: 最小文件大小 – 排除小于 n 字节的文件。

以下是所有命令的列表: https://wmoore.wordpress.com/2009/09/01/robocopy-command-line-switches/

相关内容