從備份中取代小於 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/

相關內容