バックアップから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/

関連情報