Robocopy Log: Find Failed Files and Copy Them Again (PowerShell GUI)

Advertisement
Robocopy log: find failed files and copy them again File Operations
Advertisement

You want to find out which files robocopy failed to copy. The log should tell you, but when you search it for "ERROR", the same file shows up once for every retry, and files that failed once and then copied fine on a retry show up too.

So I wrote a PowerShell tool that reads the log and lists only the files and folders that were still failing at the end, with the reason and a likely cause. One window does three things:

  • Drop an existing log onto the window and you get the list (English or Japanese logs, appended logs too)
  • Pick a source and destination, run robocopy from the window, and the list appears when it finishes (options are check boxes, no switches to type)
  • Copy only the failed items again, or save the list as a CSV for Excel

You paste it into PowerShell and the window opens. Nothing to install and no admin rights needed.

The tool window. Source and destination are set at the top, robocopy has run, and the failed files and folder are listed below with reasons
A backup of a team share, run from the tool. When it finished, the two files and one folder that were still failing were listed. The date in the Run box is in Japanese because my test PC runs Japanese Windows

How to read a robocopy log

With /LOG or /UNILOG, robocopy writes what it did to a text file. Each copied file gets one line, problems get a different kind of line, and a summary table at the end counts files by result.

Log line Meaning Action needed?
New File, Newer, Older Copied (new file, source is newer, source is older) No
ERROR + number The copy failed. The reason is on the next line Yes, unless a retry worked
Waiting … Retrying… Robocopy will wait and try again Not known yet
*EXTRA File, *EXTRA Dir Exists only in the destination Check whether it can go (/MIR deletes it)
*MISMATCH The same name is a file on one side and a folder on the other Yes
same, older, named, and other lowercase labels (only with /V) Not copied (unchanged, excluded, and so on) No

The FAILED column of the summary is the number of files and folders that failed, and if it is not 0, the exit code is 8 or higher (see Robocopy Exit Codes Explained). Skipped means unchanged files that did not need copying, which is fine. The names of skipped files appear in the log only with /V.

Isn't searching the log for "ERROR" enough?

You could keep running robocopy as usual and search the log for "ERROR" afterward. I tried that on a backup of a team share (570 files) that ran twice, with the second run appended to the same log.

PowerShell window showing the result of searching a robocopy log for ERROR, with the same files repeated many times
Searching the log for "ERROR" returned 31 lines. In the latest run, only two files and one folder were still failing

The search did not give a list of failures, for four reasons.

  • Each retry logs the same error again. This test used /R:3, so one file produced four lines. The default is 1,000,000 retries with a 30-second wait, so one file that someone keeps open fills the log with the same line
  • Files that succeeded on a retry still leave an error behind. Weekly_Meeting_1201.docx was in use on the first try and copied on the second. The only clue in the log is that the file line appears once more after the error, with no error after it
  • If you append with /LOG+ or /UNILOG+, earlier runs show up as well
  • The reason is on the line after the error, and *EXTRA lines only show the file name, so you have to scroll up to the folder line to see where it is

Here is what a successful retry looks like in the log (part of the path is shortened to "…").

	    New File  		   12000	Weekly_Meeting_1201.docx
2026/12/02 00:33:08 ERROR 32 (0x00000020) Copying File D:\…\TeamShare\03_Minutes\Weekly_Meeting_1201.docx
The process cannot access the file because it is being used by another process.
Waiting 2 seconds... Retrying...
	    New File  		   12000	Weekly_Meeting_1201.docx

The tool follows this sequence for each file and marks a file as failed only when its last attempt failed. It also compares its counts with the summary table at the end of the log and shows both at the top of the window.

The tool: list the failures from a log (and run robocopy too)

Open PowerShell (5.1 or 7) and paste the whole script. There is nothing to edit in the script. You pick the source, destination, and options on the window. To save it as a .ps1 file and run it instead, see how to run PowerShell code you copied.

# Run robocopy from a window, then list the failed, mismatched, extra, and skipped files (PowerShell 5.1 / 7)
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

# Nothing to edit here. Pick the source, destination, and options on the window, and save the ones you use often as a named set

# Likely causes by error number (Windows system error codes)
$hints = @{
    2    = 'File not found. It was deleted or renamed during the copy'
    3    = 'Folder not found. Wrong path, or the drive or NAS went offline'
    5    = 'Access denied. No permission, or the file is read-only'
    32   = 'In use by another app, e.g. still open in Excel'
    33   = 'Another app has locked part of the file'
    53   = 'Network path not found. Check that the NAS or server is on and the name is right'
    64   = 'The network connection dropped during the copy'
    67   = 'Share name not found'
    112  = 'Not enough free space on the destination'
    121  = 'Network timeout'
    1314 = 'Missing privilege. /COPYALL or similar tried to copy permissions too'
    1326 = 'Wrong user name or password for the NAS or server'
    1392 = 'The file or folder is corrupted and unreadable'
}
$actions = @{
    'Copying File'                    = 'Copying a file'
    'Accessing Source Directory'      = 'Opening the source folder'
    'Accessing Destination Directory' = 'Opening the destination folder'
    'Scanning Source Directory'       = 'Listing the source folder'
    'Scanning Destination Directory'  = 'Listing the destination folder'
    'Creating Destination Directory'  = 'Creating the destination folder'
    'Deleting Extra File'             = 'Deleting an extra file'
    'Deleting Extra Directory'        = 'Deleting an extra folder'
    'ファイルをコピーしています'                 = 'Copying a file'
    'コピー先ディレクトリにアクセスしています'       = 'Opening the destination folder'
    'コピー元ディレクトリにアクセスしています'       = 'Opening the source folder'
}
# Why a file was not copied (lowercase labels, shown only with /V)
$skipReasons = @{
    'same'    = 'Same file (unchanged)'
    'older'   = 'Destination is newer (/XO)'
    'newer'   = 'Source is newer (/XN)'
    'changed' = 'Changed attributes (/XC)'
    'named'   = 'Excluded by name (/XF or /XD)'
    'lonely'  = 'Only in the source (/XL)'
    'tweaked' = 'Only the attributes differ'
    '名前の付いた' = 'Excluded by name (/XF or /XD)'
}
# On Japanese Windows, robocopy prints English when run from a console and Japanese when run without one (e.g. from Task Scheduler). Accept both
$headNames = @{ 'Started' = 'Started'; 'Source' = 'Source'; 'Dest' = 'Dest'; 'Options' = 'Options'; '開始' = 'Started'; 'コピー元' = 'Source'; 'コピー先' = 'Dest'; 'オプション' = 'Options' }

# Read the log. /unilog writes UTF-16, /log writes the OEM code page
function Read-LogLines($path) {
    # Open with a share mode so the log can be read while robocopy is still writing it
    $fs = New-Object IO.FileStream($path, 'Open', 'Read', 'ReadWrite')
    try { $b = New-Object byte[] $fs.Length; [void]$fs.Read($b, 0, $b.Length) } finally { $fs.Dispose() }
    if ($b.Length -ge 2 -and $b[0] -eq 0xFF -and $b[1] -eq 0xFE) {
        $text = [Text.Encoding]::Unicode.GetString($b, 2, $b.Length - 2)
    } elseif ($b.Length -ge 3 -and $b[0] -eq 0xEF -and $b[1] -eq 0xBB -and $b[2] -eq 0xBF) {
        $text = [Text.Encoding]::UTF8.GetString($b, 3, $b.Length - 3)
    } else {
        try { $text = (New-Object Text.UTF8Encoding($false, $true)).GetString($b) }
        catch {
            $oem = [Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage
            $text = [Text.Encoding]::GetEncoding($oem).GetString($b)
        }
    }
    # /unilog+ leaves a BOM at each appended run, so remove it. Also drop the progress text (overwritten with CR) written without /NP
    $text = $text.Replace([string][char]0xFEFF, '')
    return @($text -split "`r?`n" | ForEach-Object { ($_ -split "`r")[0] })
}

# Split the log into runs at each "ROBOCOPY :: Robust File Copy" header (for logs appended with /log+)
function Split-Runs($lines) {
    $runs = New-Object System.Collections.Generic.List[object]
    $cur = $null
    foreach ($line in $lines) {
        if ($line -match '^\s*ROBOCOPY\s+::' -or $null -eq $cur) {
            $cur = [pscustomobject]@{ Lines = New-Object System.Collections.Generic.List[string]; Started = ''; Source = ''; Dest = ''; Options = '' }
            $runs.Add($cur)
            if ($line -match 'ROBOCOPY\s+::') { continue }
        }
        $cur.Lines.Add($line)
        if ($line -match '^\s*(Started|Source|Dest|Options|開始|コピー元|コピー先|オプション)\s?:\s(.*)$') {
            $k = $headNames[$Matches[1]]
            if ($cur.$k -eq '') { $cur.$k = $Matches[2].Trim() }
        }
    }
    return @($runs | Where-Object { $_.Lines.Count -gt 3 })
}

# Turn one run into a list with one row per file
function Read-Run($run) {
    $rows = New-Object System.Collections.Generic.List[object]
    $sum = @{}
    $dir = $run.Source
    $err = $null   # The last error. Whether a retry fixed it is decided by the lines that follow
    $tries = @{}
    $add = {
        param($kind, $target, $path, $code, $action, $msg, $hint, $time)
        $rows.Add([pscustomobject]@{
            'Type' = $kind; 'Item' = $target; 'Path' = $path; 'Error' = $code; 'Operation' = $action
            'Log message' = $msg; 'Likely cause' = $hint; 'Attempts' = $tries[$path]; 'Time' = $time
            _Src = $run.Source; _Dst = $run.Dest; _Opt = $run.Options })   # the three _ fields are used when copying again
    }
    $finish = {
        param([bool]$failed)
        if ($null -eq $err) { return }
        if ($failed) {
            $act = $actions[$err.Action]; if (-not $act) { $act = $err.Action }
            & $add 'Failed' $err.Target $err.Path ('{0} ({1})' -f $err.Code, $err.Hex) $act $err.Msg $hints[[int]$err.Code] $err.Time
        } elseif ($err.Target -eq 'File') {
            & $add 'Copied' 'File' $err.Path '' '' ('Succeeded on retry (attempt {0})' -f ($tries[$err.Path] + 1)) '' ''
        }
        Set-Variable err $null -Scope 1
    }
    $toDest = {
        param($p)
        if ($run.Source -and $run.Dest -and $p.StartsWith($run.Source, [StringComparison]::OrdinalIgnoreCase)) {
            return $run.Dest + $p.Remove(0, $run.Source.Length)
        }
        return $p
    }
    $wantMsg = $false
    $opts = ' ' + $run.Options + ' '
    foreach ($line in $run.Lines) {
        if ($wantMsg) {
            if ($line.Trim() -ne '') { $err.Msg = $line.Trim(); $wantMsg = $false }
            continue
        }
        # Error line: "2026/12/01 23:49:55 ERROR 32 (0x00000020) Copying File D:\...\a.xlsx"
        if ($line -match '^(\d{4}/\d\d/\d\d \d\d:\d\d:\d\d) (?:ERROR|エラー) (\d+) \((0x[0-9A-Fa-f]+)\) (.*?) ?((?:[A-Za-z]:\\|\\\\).*)$') {
            $e = [pscustomobject]@{ Time = $Matches[1]; Code = $Matches[2]; Hex = $Matches[3]; Action = $Matches[4].Trim()
                Path = $Matches[5].Trim(); Msg = ''; Retry = $false; Target = 'File' }
            if ($e.Path.EndsWith('\') -or $e.Action -match 'Director|ディレクトリ') { $e.Target = 'Folder' }
            if ($null -ne $err -and $err.Path -ne $e.Path) { & $finish (-not $err.Retry) }
            $tries[$e.Path] = [int]$tries[$e.Path] + 1
            Set-Variable err $e
            $wantMsg = $true
            continue
        }
        if ($line -match '^Waiting \d+ seconds|^\d+ 秒間待機しています') { if ($err) { $err.Retry = $true }; continue }
        if ($line -match 'RETRY LIMIT EXCEEDED|再試行が制限回数を超えました') { & $finish $true; continue }
        # Summary table: "Files :  13  9  0  1  3  1" (Total Copied Skipped Mismatch FAILED Extras)
        if ($line -match '^\s*(Dirs|Files|ディレクトリ|ファイル)\s*:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$') {
            & $finish (-not ($err -and $err.Retry))
            $m = $Matches.Clone()
            $key = if ($m[1] -eq 'Dirs' -or $m[1] -eq 'ディレクトリ') { 'Dirs' } else { 'Files' }
            $sum[$key] = [pscustomobject]@{ Total = [int]$m[2]; Copied = [int]$m[3]; Skipped = [int]$m[4]
                Mismatch = [int]$m[5]; Failed = [int]$m[6]; Extras = [int]$m[7] }
            continue
        }
        # Folder line: "<tab>  New Dir  5<tab>D:\...\Quotes\"
        if ($line -match '^\t\s*(.*?)\s*(-?\d+)\t(.+\\)$') {
            $cls = $Matches[1]; $path = $Matches[3]
            & $finish (-not ($err -and $err.Retry))
            if ($cls -like '*EXTRA*') { & $add 'Extra' 'Folder' $path '' '' 'Only in the destination' '' ''; continue }
            if ($cls -cmatch '^[a-z]') { & $add 'Skipped' 'Folder' $path '' '' $cls $skipReasons[($cls -split ' ')[0]] ''; continue }
            $dir = $path
            continue
        }
        # File line: "<tab>    New File  <tab><tab>  1000<tab>Quote_1.xlsx" (/TS adds a timestamp, /FP gives the full path)
        if ($line -match '^\t\s*(.*?)\s*\t\t\s*([\d.]+(?: [kmgt])?)(?: \d{4}/\d\d/\d\d \d\d:\d\d:\d\d)?\t(.+)$') {
            $cls = $Matches[1]; $size = $Matches[2]; $name = $Matches[3]
            if ($name -match '^(?:[A-Za-z]:\\|\\\\)') { $path = $name } else { $path = $dir + $name }
            if ($null -ne $err) {
                if ($err.Retry -and $err.Path -eq $path) { continue }   # the retry attempt of the same file
                & $finish (-not $err.Retry)
            }
            if ($cls -like '*EXTRA*') {
                if ($name -notmatch '^(?:[A-Za-z]:\\|\\\\)') { $path = & $toDest $path }
                & $add 'Extra' 'File' $path '' '' 'Only in the destination' '' ''
            } elseif ($cls -like '*MISMATCH*' -or $cls -like '*不一致*') {
                & $add 'Mismatch' 'File' $path '' '' 'Same name is a file on one side and a folder on the other' '' ''
            } elseif ($cls -cmatch '^[a-z]' -or $cls -eq '名前の付いた') {
                & $add 'Skipped' 'File' $path '' '' $cls $skipReasons[$cls] ''
            } elseif (($cls -eq '古い' -and $opts -match ' /XO ') -or ($cls -eq '新しい' -and $opts -match ' /XN ')) {
                # Japanese labels have no upper/lower case, so use /XO or /XN to tell a skipped file from a copied one
                & $add 'Skipped' 'File' $path '' '' $cls $(if ($cls -eq '古い') { $skipReasons['older'] } else { $skipReasons['newer'] }) ''
            } else {
                & $add 'Copied' 'File' $path '' '' $cls '' ''
            }
            continue
        }
    }
    & $finish (-not ($err -and $err.Retry))
    # For Copied rows, drop files that failed later and keep only the last row when a file appears more than once
    $failed = @{}; $last = @{}
    foreach ($r in $rows) { if ($r.'Type' -eq 'Failed') { $failed[$r.'Path'] = $true } elseif ($r.'Type' -eq 'Copied') { $last[$r.'Path'] = $r } }
    $list = @($rows | Where-Object { $_.'Type' -ne 'Copied' -or (-not $failed[$_.'Path'] -and [object]::ReferenceEquals($last[$_.'Path'], $_)) })
    return [pscustomobject]@{ Rows = $list; Summary = $sum; NoSummary = [int]($sum.Count -eq 0) }
}

# Combine all runs (useful for retry logs, where each run is short)
function Read-AllRuns($runs) {
    $rows = New-Object System.Collections.Generic.List[object]; $sum = @{}; $no = 0
    foreach ($r in $runs) {
        $x = Read-Run $r
        foreach ($row in $x.Rows) { $rows.Add($row) }
        $no += $x.NoSummary
        foreach ($k in $x.Summary.Keys) {
            if (-not $sum[$k]) { $sum[$k] = [pscustomobject]@{ Total = 0; Copied = 0; Skipped = 0; Mismatch = 0; Failed = 0; Extras = 0 } }
            foreach ($q in 'Total', 'Copied', 'Skipped', 'Mismatch', 'Failed', 'Extras') { $sum[$k].$q += $x.Summary[$k].$q }
        }
    }
    return [pscustomobject]@{ Rows = $rows.ToArray(); Summary = $sum; NoSummary = $no }
}

# Compare the extracted counts with the summary table at the end of the log
function Get-CheckText($res) {
    $n = { param($k, $t) @($res.Rows | Where-Object { $_.'Type' -eq $k -and $_.'Item' -eq $t }).Count }
    $f = $res.Summary['Files']; $d = $res.Summary['Dirs']
    $s = 'Failed: {0} files, {1} folders   Mismatch: {2}   Extra: {3} files, {4} folders   Skipped: {5}' -f `
        (& $n 'Failed' 'File'), (& $n 'Failed' 'Folder'), (& $n 'Mismatch' 'File'), (& $n 'Extra' 'File'), (& $n 'Extra' 'Folder'), (& $n 'Skipped' 'File')
    if ($f -and $d) {
        $s += "`r`nLog summary:  Failed {0} files, {1} folders   Mismatch {2}   Extra {3} files, {4} folders   Skipped {5}" -f $f.Failed, $d.Failed, $f.Mismatch, $f.Extras, $d.Extras, $f.Skipped
        if ($f.Skipped -gt (& $n 'Skipped' 'File')) { $s += ' (skipped file names appear in the log only with /V)' }
        if ($res.NoSummary -gt 0) { $s += ' ({0} run(s) have no summary table)' -f $res.NoSummary }
    } else {
        $s += "`r`nNo summary table in the log (the run may have stopped partway)"
    }
    return $s
}

# ---- Window ----
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Run robocopy and list the failed files'
$form.Size = New-Object System.Drawing.Size(1100, 850)
$form.Font = New-Object System.Drawing.Font('Segoe UI', 9)

# Top: run robocopy
$set = New-Object System.Windows.Forms.GroupBox; $set.Text = 'Run robocopy'; $set.Dock = 'Top'; $set.Height = 252
$set.Width = $form.ClientSize.Width    # match the window width first so right-anchored controls stay inside the window
# Save a source, destination, and copy options you use often as a named set, then fill them in by picking the set
$lblSet = New-Object System.Windows.Forms.Label; $lblSet.Text = 'Saved set:'; $lblSet.Location = '10,25'; $lblSet.AutoSize = $true; $set.Controls.Add($lblSet)
$cmbSet = New-Object System.Windows.Forms.ComboBox; $cmbSet.DropDownStyle = 'DropDownList'; $cmbSet.Location = '95,22'; $cmbSet.Width = 300; $set.Controls.Add($cmbSet)
$btnSaveSet = New-Object System.Windows.Forms.Button; $btnSaveSet.Text = 'Save current inputs as a set...'; $btnSaveSet.Location = '405,20'; $btnSaveSet.Width = 210; $set.Controls.Add($btnSaveSet)
$btnDelSet = New-Object System.Windows.Forms.Button; $btnDelSet.Text = 'Delete this set'; $btnDelSet.Location = '625,20'; $btnDelSet.Width = 130; $btnDelSet.Enabled = $false; $set.Controls.Add($btnDelSet)
$lblS = New-Object System.Windows.Forms.Label; $lblS.Text = 'Source:'; $lblS.Location = '10,57'; $lblS.AutoSize = $true; $set.Controls.Add($lblS)
$txtSrc = New-Object System.Windows.Forms.TextBox; $txtSrc.Location = '95,54'; $txtSrc.Width = 880; $txtSrc.Anchor = 'Top,Left,Right'; $set.Controls.Add($txtSrc)
$btnSrc = New-Object System.Windows.Forms.Button; $btnSrc.Text = 'Browse...'; $btnSrc.Location = '985,52'; $btnSrc.Width = 85; $btnSrc.Anchor = 'Top,Right'; $set.Controls.Add($btnSrc)
$lblD = New-Object System.Windows.Forms.Label; $lblD.Text = 'Destination:'; $lblD.Location = '10,87'; $lblD.AutoSize = $true; $set.Controls.Add($lblD)
$txtDst = New-Object System.Windows.Forms.TextBox; $txtDst.Location = '95,84'; $txtDst.Width = 880; $txtDst.Anchor = 'Top,Left,Right'; $set.Controls.Add($txtDst)
$btnDst = New-Object System.Windows.Forms.Button; $btnDst.Text = 'Browse...'; $btnDst.Location = '985,82'; $btnDst.Width = 85; $btnDst.Anchor = 'Top,Right'; $set.Controls.Add($btnDst)
# Options are picked, not typed. Left as is, they give /E /R:2 /W:5 (subfolders, and on failure wait 5 seconds and retry up to 2 times)
function New-Row($y) {
    $r = New-Object System.Windows.Forms.FlowLayoutPanel; $r.Location = New-Object System.Drawing.Point(90, $y); $r.Size = '980,28'
    $r.WrapContents = $false; $r.Anchor = 'Top,Left,Right'; $set.Controls.Add($r); return $r
}
function Add-Check($row, $text, [bool]$on) {
    $c = New-Object System.Windows.Forms.CheckBox; $c.Text = $text; $c.AutoSize = $true; $c.Checked = $on; $c.Margin = '3,4,14,0'; $row.Controls.Add($c); return $c
}
function Add-Text($row, $text) {
    $l = New-Object System.Windows.Forms.Label; $l.Text = $text; $l.AutoSize = $true; $l.Margin = '3,7,0,0'; $row.Controls.Add($l)
}
function Add-Num($row, $value, $max) {
    $n = New-Object System.Windows.Forms.NumericUpDown; $n.Minimum = 0; $n.Maximum = $max; $n.Value = $value; $n.Width = 50; $n.Margin = '3,3,0,0'; $row.Controls.Add($n); return $n
}
$lblO = New-Object System.Windows.Forms.Label; $lblO.Text = 'How to copy:'; $lblO.Location = '10,119'; $lblO.AutoSize = $true; $set.Controls.Add($lblO)
$row1 = New-Row 114
$chkSub = Add-Check $row1 'Include subfolders' $true
$chkEmpty = Add-Check $row1 'Create empty folders too' $true
Add-Text $row1 'On failure, retry up to'; $numR = Add-Num $row1 2 99; Add-Text $row1 'times, waiting'; $numW = Add-Num $row1 5 60; Add-Text $row1 'seconds each time'
$row2 = New-Row 142
$chkXO = Add-Check $row2 'Do not overwrite files that are newer in the destination' $false
$chkMir = Add-Check $row2 'Mirror: delete files that exist only in the destination (asks first)' $false
$row3 = New-Row 170
$chkMore = Add-Check $row3 'Add more options (advanced)' $false
$txtExtra = New-Object System.Windows.Forms.TextBox; $txtExtra.Width = 300; $txtExtra.Visible = $false; $row3.Controls.Add($txtExtra)
$lblL = New-Object System.Windows.Forms.Label; $lblL.Text = 'Log folder:'; $lblL.Location = '10,207'; $lblL.AutoSize = $true; $set.Controls.Add($lblL)
$txtLogDir = New-Object System.Windows.Forms.TextBox; $txtLogDir.Location = '95,204'; $txtLogDir.Width = 500; $set.Controls.Add($txtLogDir)
if (-not $txtLogDir.Text) { $txtLogDir.Text = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'robocopy-log' }
$btnLogDir = New-Object System.Windows.Forms.Button; $btnLogDir.Text = 'Browse...'; $btnLogDir.Location = '605,202'; $btnLogDir.Width = 85; $set.Controls.Add($btnLogDir)
$btnRun = New-Object System.Windows.Forms.Button; $btnRun.Text = 'Run robocopy'; $btnRun.Location = '710,200'; $btnRun.Size = '150,28'; $set.Controls.Add($btnRun)
$btnStop = New-Object System.Windows.Forms.Button; $btnStop.Text = 'Stop'; $btnStop.Location = '870,200'; $btnStop.Size = '80,28'; $btnStop.Enabled = $false; $set.Controls.Add($btnStop)
$lblStatus = New-Object System.Windows.Forms.Label; $lblStatus.Location = '10,232'; $lblStatus.Size = '1060,16'; $lblStatus.Anchor = 'Top,Left,Right'; $set.Controls.Add($lblStatus)
# Turn the choices into robocopy options
function Get-Options {
    $o = @()
    if ($chkSub.Checked) { if ($chkEmpty.Checked) { $o += '/E' } else { $o += '/S' } }
    $o += '/R:{0}' -f [int]$numR.Value
    $o += '/W:{0}' -f [int]$numW.Value
    if ($chkXO.Checked) { $o += '/XO' }
    if ($chkMir.Checked) { $o += '/MIR' }
    if ($chkMore.Checked -and $txtExtra.Text.Trim()) { $o += $txtExtra.Text.Trim() }
    return ($o -join ' ')
}
function Show-Options {
    if ($script:proc) { return }
    $lblStatus.Text = 'Will run: robocopy source destination ' + (Get-Options) + ' /NP /UNILOG+:log'
}
$chkMir.Add_CheckedChanged({
    # Mirror always includes subfolders and empty folders, so keep those two checked
    if ($chkMir.Checked) { $chkSub.Checked = $true; $chkEmpty.Checked = $true }
    $chkSub.Enabled = -not $chkMir.Checked; $chkEmpty.Enabled = (-not $chkMir.Checked) -and $chkSub.Checked
})
$chkSub.Add_CheckedChanged({ $chkEmpty.Enabled = $chkSub.Checked -and -not $chkMir.Checked })
$chkMore.Add_CheckedChanged({ $txtExtra.Visible = $chkMore.Checked })
foreach ($c in $chkSub, $chkEmpty, $chkXO, $chkMir, $chkMore) { $c.Add_CheckedChanged({ Show-Options }) }
foreach ($c in $numR, $numW) { $c.Add_ValueChanged({ Show-Options }) }
$txtExtra.Add_TextChanged({ Show-Options })
# Where sets are kept (your AppData folder). Mirror is never saved in a set, to be safe
$settingsFile = Join-Path $env:APPDATA 'robocopy-failed-list.json'
function Read-Sets {
    $o = [pscustomobject]@{ Last = ''; Sets = @() }
    if (Test-Path -LiteralPath $settingsFile) {
        try { $j = [IO.File]::ReadAllText($settingsFile) | ConvertFrom-Json; $o.Last = [string]$j.Last; $o.Sets = @($j.Sets | Where-Object { $_.Name }) } catch { }
    }
    return $o
}
function Write-Sets {
    try { [IO.File]::WriteAllText($settingsFile, (ConvertTo-Json $script:sets -Depth 4), (New-Object Text.UTF8Encoding($false))) }
    catch { [void][System.Windows.Forms.MessageBox]::Show("Could not save the sets: $settingsFile", 'robocopy') }
}
function Fill-SetList($select) {
    $script:sets = Read-Sets
    $cmbSet.Items.Clear(); [void]$cmbSet.Items.Add('(choose a set)')
    foreach ($x in $script:sets.Sets) { [void]$cmbSet.Items.Add([string]$x.Name) }
    $cmbSet.SelectedIndex = [Math]::Max(0, $cmbSet.Items.IndexOf([string]$select))
}
# Small window that asks for the set name
function Read-SetName($initial) {
    $f = New-Object System.Windows.Forms.Form; $f.Text = 'Set name'; $f.Size = '440,160'; $f.StartPosition = 'CenterParent'; $f.Font = $form.Font
    $f.FormBorderStyle = 'FixedDialog'; $f.MaximizeBox = $false; $f.MinimizeBox = $false
    $l = New-Object System.Windows.Forms.Label; $l.Text = 'Name (e.g. Daily team share backup)'; $l.Location = '10,12'; $l.AutoSize = $true; $f.Controls.Add($l)
    $t = New-Object System.Windows.Forms.TextBox; $t.Location = '10,38'; $t.Width = 400; $t.Text = $initial; $f.Controls.Add($t)
    $ok = New-Object System.Windows.Forms.Button; $ok.Text = 'OK'; $ok.Location = '240,75'; $ok.DialogResult = 'OK'; $f.Controls.Add($ok)
    $cancel = New-Object System.Windows.Forms.Button; $cancel.Text = 'Cancel'; $cancel.Location = '330,75'; $cancel.DialogResult = 'Cancel'; $f.Controls.Add($cancel)
    $f.AcceptButton = $ok; $f.CancelButton = $cancel
    if ($f.ShowDialog($form) -ne 'OK') { return '' }
    return $t.Text.Trim()
}
$cmbSet.Add_SelectedIndexChanged({
    $btnDelSet.Enabled = $cmbSet.SelectedIndex -gt 0
    if ($cmbSet.SelectedIndex -le 0) { return }
    $x = $script:sets.Sets | Where-Object { $_.Name -eq [string]$cmbSet.SelectedItem } | Select-Object -First 1
    if (-not $x) { return }
    $chkMir.Checked = $false
    $txtSrc.Text = $x.Source; $txtDst.Text = $x.Dest; if ($x.LogDir) { $txtLogDir.Text = $x.LogDir }
    $chkSub.Checked = [bool]$x.Sub; $chkEmpty.Checked = [bool]$x.Empty
    $numR.Value = [Math]::Min(99, [int]$x.R); $numW.Value = [Math]::Min(60, [int]$x.W)
    $chkXO.Checked = [bool]$x.XO; $txtExtra.Text = [string]$x.Extra; $chkMore.Checked = [bool]$x.More
    # Start with this set selected the next time the window opens
    $script:sets.Last = $x.Name; Write-Sets
})
$btnSaveSet.Add_Click({
    $name = Read-SetName $(if ($cmbSet.SelectedIndex -gt 0) { [string]$cmbSet.SelectedItem } else { '' })
    if (-not $name) { return }
    $others = @($script:sets.Sets | Where-Object { $_.Name -ne $name })
    if ($others.Count -lt @($script:sets.Sets).Count) {
        $msg = "Overwrite the set $name with the current inputs?"
        if ([System.Windows.Forms.MessageBox]::Show($msg, 'robocopy', 'YesNo', 'Question') -ne 'Yes') { return }
    }
    $new = [pscustomobject][ordered]@{ Name = $name; Source = $txtSrc.Text.Trim(); Dest = $txtDst.Text.Trim(); LogDir = $txtLogDir.Text.Trim()
        Sub = $chkSub.Checked; Empty = $chkEmpty.Checked; R = [int]$numR.Value; W = [int]$numW.Value; XO = $chkXO.Checked; More = $chkMore.Checked; Extra = $txtExtra.Text }
    $script:sets = [pscustomobject]@{ Last = $name; Sets = @($others + $new) }
    Write-Sets; Fill-SetList $name
})
$btnDelSet.Add_Click({
    if ($cmbSet.SelectedIndex -le 0) { return }
    $name = [string]$cmbSet.SelectedItem
    $msg = "Delete the set $name? (Only the saved set is removed. No files in the source or destination are deleted.)"
    if ([System.Windows.Forms.MessageBox]::Show($msg, 'robocopy', 'YesNo', 'Question') -ne 'Yes') { return }
    $script:sets = [pscustomobject]@{ Last = ''; Sets = @($script:sets.Sets | Where-Object { $_.Name -ne $name }) }
    Write-Sets; Fill-SetList ''
})
$script:sets = Read-Sets
Fill-SetList $script:sets.Last
Show-Options

# Middle: results (loaded automatically when a run finishes; you can also open an older log)
$top = New-Object System.Windows.Forms.Panel; $top.Dock = 'Top'; $top.Height = 112; $top.Width = $form.ClientSize.Width
$lbl = New-Object System.Windows.Forms.Label; $lbl.Text = 'Log file:'; $lbl.Location = '10,13'; $lbl.AutoSize = $true; $top.Controls.Add($lbl)
$txtPath = New-Object System.Windows.Forms.TextBox; $txtPath.Location = '95,10'; $txtPath.Width = 880; $txtPath.Anchor = 'Top,Left,Right'; $top.Controls.Add($txtPath)
$btnBrowse = New-Object System.Windows.Forms.Button; $btnBrowse.Text = 'Open log...'; $btnBrowse.Location = '985,8'; $btnBrowse.Width = 85; $btnBrowse.Anchor = 'Top,Right'; $top.Controls.Add($btnBrowse)
$lbl2 = New-Object System.Windows.Forms.Label; $lbl2.Text = 'Run:'; $lbl2.Location = '10,45'; $lbl2.AutoSize = $true; $top.Controls.Add($lbl2)
$cmbRun = New-Object System.Windows.Forms.ComboBox; $cmbRun.DropDownStyle = 'DropDownList'; $cmbRun.Location = '95,42'; $cmbRun.Width = 600; $top.Controls.Add($cmbRun)
$checks = @{}
$x = 710
foreach ($k in 'Failed', 'Mismatch', 'Extra', 'Skipped', 'Copied') {
    $c = New-Object System.Windows.Forms.CheckBox; $c.Text = $k; $c.AutoSize = $true; $c.Location = New-Object System.Drawing.Point($x, 44)
    $c.Checked = ($k -ne 'Copied'); $top.Controls.Add($c); $checks[$k] = $c; $x += 95
}
$lblSum = New-Object System.Windows.Forms.Label; $lblSum.Location = '10,72'; $lblSum.Size = '1060,36'; $lblSum.Anchor = 'Top,Left,Right'; $top.Controls.Add($lblSum)

$bottom = New-Object System.Windows.Forms.Panel; $bottom.Dock = 'Bottom'; $bottom.Height = 44
$btnCsv = New-Object System.Windows.Forms.Button; $btnCsv.Text = 'Save as CSV and open in Excel'; $btnCsv.Location = '10,8'; $btnCsv.Width = 200; $bottom.Controls.Add($btnCsv)
$btnOpen = New-Object System.Windows.Forms.Button; $btnOpen.Text = 'Open selected location'; $btnOpen.Location = '220,8'; $btnOpen.Width = 170; $bottom.Controls.Add($btnOpen)
$btnRetry = New-Object System.Windows.Forms.Button; $btnRetry.Text = 'Copy only the failed items again'; $btnRetry.Location = '400,8'; $btnRetry.Width = 220; $bottom.Controls.Add($btnRetry)

$grid = New-Object System.Windows.Forms.DataGridView
$grid.Dock = 'Fill'; $grid.ReadOnly = $true; $grid.AllowUserToAddRows = $false; $grid.SelectionMode = 'FullRowSelect'
$grid.RowHeadersVisible = $false
# Run settings at the top, results below them, and the list in the middle
$form.Controls.AddRange(@($grid, $top, $set, $bottom))

$script:runs = @(); $script:result = $null

function Show-Rows {
    if ($null -eq $script:result) { return }
    $table = New-Object System.Data.DataTable
    $cols = 'Type', 'Item', 'Path', 'Error', 'Operation', 'Log message', 'Likely cause', 'Attempts', 'Time'
    foreach ($c in $cols) { [void]$table.Columns.Add($c) }
    foreach ($r in $script:result.Rows) {
        if (-not $checks[$r.'Type'].Checked) { continue }
        $row = $table.NewRow(); foreach ($c in $cols) { $row[$c] = [string]$r.$c }; $table.Rows.Add($row)
    }
    $grid.DataSource = $table
    # Long paths push the other columns off screen, so cap the Path column (hover a cell to see the full path)
    $grid.AutoResizeColumns()
    if ($grid.Columns.Count -gt 2 -and $grid.Columns[2].Width -gt 520) { $grid.Columns[2].Width = 520 }
    $lblSum.Text = Get-CheckText $script:result
}
function Show-Run {
    if ($cmbRun.SelectedIndex -lt 0) { return }
    if ($cmbRun.SelectedIndex -ge $script:runs.Count) { $script:result = Read-AllRuns $script:runs }
    else { $script:result = Read-Run $script:runs[$cmbRun.SelectedIndex] }
    Show-Rows
}
function Open-Log($path, [switch]$All, [switch]$FromRun) {
    if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
        [void][System.Windows.Forms.MessageBox]::Show("Choose a log file (a folder or a missing file cannot be read).`r`n`r`n$path", 'robocopy'); return
    }
    $lines = Read-LogLines $path
    # Every robocopy run starts with a ROBOCOPY :: header. Without one, say so instead of reading the file
    if (-not ($lines -match '^\s*ROBOCOPY\s+::')) {
        [void][System.Windows.Forms.MessageBox]::Show("This does not look like a robocopy log (no ROBOCOPY :: header).`r`n`r`n$path", 'robocopy'); return
    }
    $txtPath.Text = $path
    $form.Cursor = 'WaitCursor'
    try {
        $script:runs = @(Split-Runs $lines)
        $cmbRun.Items.Clear()
        $i = 1
        foreach ($r in $script:runs) {
            # Leave out a start time whose date has lost its separators (English robocopy on Japanese Windows)
            $st = if ($r.Started -match '^\d{7,8}\s') { '' } else { $r.Started }
            [void]$cmbRun.Items.Add(('Run {0}  {1}  {2} -> {3}' -f $i, $st, $r.Source, $r.Dest)); $i++
        }
        if ($script:runs.Count -gt 1) { [void]$cmbRun.Items.Add('All runs combined') }
        if ($All -and $script:runs.Count -gt 1) { $cmbRun.SelectedIndex = $cmbRun.Items.Count - 1 }
        elseif ($script:runs.Count -gt 0) { $cmbRun.SelectedIndex = $script:runs.Count - 1 }    # the last (newest) run
        # Do not leave the previous run's result in the status line
        if (-not $FromRun) { $lblStatus.Text = 'Opened log: ' + $path }
    } finally { $form.Cursor = 'Default' }
}

# ---- Running robocopy (in the background so the window stays responsive; checks every 0.5 seconds) ----
$script:queue = New-Object System.Collections.Queue
$script:proc = $null
$timer = New-Object System.Windows.Forms.Timer; $timer.Interval = 500
function Get-ExitText($code) {
    if ($script:stopped) { return 'Stopped partway (the log ends where it stopped)' }
    $t = @()
    if ($code -band 16) { $t += 'Fatal error (check the paths and permissions)' }
    if ($code -band 8) { $t += 'Some items failed to copy' }
    if ($code -band 4) { $t += 'Some items are mismatched' }
    if ($code -band 2) { $t += 'Some items exist only in the destination' }
    if ($code -band 1) { $t += 'Files were copied' }
    if ($t.Count -eq 0) { $t += 'Nothing needed copying' }
    return 'Exit code {0}: {1}' -f $code, ($t -join ', ')
}
function Fix-Arg($p) {
    $p = $p.Trim().Trim('"').TrimEnd('\')    # a trailing \ would break the quoting of the argument
    if ($p -match ':$') { $p += '\.' }        # turn a bare D: into D:\.
    return $p
}
function Start-Next {
    if ($script:queue.Count -eq 0) {
        $timer.Stop(); $script:proc = $null
        $btnRun.Enabled = $true; $btnRetry.Enabled = $true; $btnCsv.Enabled = $true; $btnOpen.Enabled = $true; $btnStop.Enabled = $false
        $lblStatus.Text = 'Finished. ' + (Get-ExitText $script:code) + '   Log: ' + $script:runLog
        if ((Get-Item -LiteralPath $script:runLog).Length -le 2) {
            # An empty log means robocopy never started (for example, a typo in More options)
            $lblStatus.Text = 'robocopy did not start (exit code {0}). Check More options.' -f $script:code
            return
        }
        Open-Log $script:runLog -All:$script:runAll -FromRun
        return
    }
    # run in this PowerShell console (only a Log File line is printed; the rest goes to the log)
    $script:proc = Start-Process robocopy.exe -ArgumentList $script:queue.Dequeue() -NoNewWindow -PassThru
    $null = $script:proc.Handle    # reading Handle makes the exit code available after the process ends
}
function Start-Robo($argList, $log, [switch]$All) {
    # /UNILOG+ on a new file may not write UTF-16, so create the file with just a UTF-16 BOM first
    [IO.File]::WriteAllBytes($log, [byte[]](0xFF, 0xFE))
    $script:queue.Clear(); foreach ($a in $argList) { $script:queue.Enqueue($a) }
    $script:runLog = $log; $script:runAll = [bool]$All; $script:code = 0; $script:stopped = $false; $script:t0 = Get-Date
    $btnRun.Enabled = $false; $btnRetry.Enabled = $false; $btnCsv.Enabled = $false; $btnOpen.Enabled = $false; $btnStop.Enabled = $true
    $lblStatus.Text = 'Running robocopy...'
    Start-Next; $timer.Start()
}
$timer.Add_Tick({
    if ($null -eq $script:proc) { return }
    if (-not $script:proc.HasExited) {
        $lblStatus.Text = 'Running robocopy... {0} s   Log: {1}' -f [int]((Get-Date) - $script:t0).TotalSeconds, $script:runLog
        return
    }
    $script:proc.WaitForExit(); $script:code = $script:code -bor $script:proc.ExitCode; $script:proc = $null
    if ($script:stopped) { $script:queue.Clear() }
    Start-Next
})
$btnStop.Add_Click({ if ($script:proc) { $script:stopped = $true; try { $script:proc.Kill() } catch {} } })
$form.Add_FormClosing({ if ($script:proc -and -not $script:proc.HasExited) { $_.Cancel = $true; [void][System.Windows.Forms.MessageBox]::Show('robocopy is still running. Stop it before closing the window.', 'robocopy') } })

$btnRun.Add_Click({
    $s = Fix-Arg $txtSrc.Text; $d = Fix-Arg $txtDst.Text; $o = Get-Options
    if (-not $s -or -not $d) { [void][System.Windows.Forms.MessageBox]::Show('Enter a source and a destination.', 'robocopy'); return }
    if (-not (Test-Path -LiteralPath $s -PathType Container)) { [void][System.Windows.Forms.MessageBox]::Show("Source not found: $s", 'robocopy'); return }
    # A destination that is the source or inside it would copy the copies again
    if ($d -eq $s -or $d.StartsWith($s + '\', [StringComparison]::OrdinalIgnoreCase)) {
        [void][System.Windows.Forms.MessageBox]::Show("The destination is the source or inside it. Choose another folder.`r`n`r`nSource: $s`r`nDestination: $d", 'robocopy'); return
    }
    if ($o -match '(?i)/(MIR|PURGE|MOVE?)\b') {
        $msg = "The options include $($Matches[0]), which deletes files that exist only in the destination or moves files out of the source.`r`n`r`nSource: $s`r`nDestination: $d`r`n`r`nRun anyway?"
        if ([System.Windows.Forms.MessageBox]::Show($msg, 'robocopy', 'YesNo', 'Warning') -ne 'Yes') { return }
    }
    $dir = $txtLogDir.Text.Trim().Trim('"')
    New-Item -ItemType Directory -Path $dir -Force | Out-Null
    $log = Join-Path $dir ('robocopy_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.log')
    Start-Robo @(('"{0}" "{1}" {2} /NP "/UNILOG+:{3}"' -f $s, $d, $o, $log)) $log
})
foreach ($pair in @(@($btnSrc, $txtSrc), @($btnDst, $txtDst), @($btnLogDir, $txtLogDir))) {
    $pair[0].Tag = $pair[1]
    $pair[0].Add_Click({
        $dlg = New-Object System.Windows.Forms.FolderBrowserDialog
        if ($this.Tag.Text -and (Test-Path -LiteralPath $this.Tag.Text)) { $dlg.SelectedPath = $this.Tag.Text }
        if ($dlg.ShowDialog() -eq 'OK') { $this.Tag.Text = $dlg.SelectedPath }
    })
}
$btnBrowse.Add_Click({
    $dlg = New-Object System.Windows.Forms.OpenFileDialog
    $dlg.Filter = 'Logs (*.log;*.txt)|*.log;*.txt|All files (*.*)|*.*'
    if ($dlg.ShowDialog() -eq 'OK') { Open-Log $dlg.FileName }
})
# Drag and drop an older log anywhere on the window to open it
function Add-Drop($c) {
    $c.AllowDrop = $true
    $c.Add_DragEnter({ if ($_.Data.GetDataPresent('FileDrop')) { $_.Effect = 'Copy' } })
    $c.Add_DragDrop({ Open-Log ($_.Data.GetData('FileDrop')[0]) })
    foreach ($k in $c.Controls) { Add-Drop $k }
}
Add-Drop $form
$txtPath.Add_KeyDown({ if ($_.KeyCode -eq 'Enter') { Open-Log $txtPath.Text.Trim('"') } })
$cmbRun.Add_SelectedIndexChanged({ Show-Run })
foreach ($c in $checks.Values) { $c.Add_CheckedChanged({ Show-Rows }) }

$btnCsv.Add_Click({
    if ($null -eq $grid.DataSource) { return }
    $dlg = New-Object System.Windows.Forms.SaveFileDialog
    $dlg.Filter = 'CSV (*.csv)|*.csv'
    $dlg.InitialDirectory = Split-Path $txtPath.Text
    $dlg.FileName = 'robocopy-report_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.csv'
    if ($dlg.ShowDialog() -ne 'OK') { return }
    # Drop the #TYPE line that 5.1 adds at the top
    $lines = $grid.DataSource | Select-Object 'Type', 'Item', 'Path', 'Error', 'Operation', 'Log message', 'Likely cause', 'Attempts', 'Time' | ConvertTo-Csv | Where-Object { $_ -notmatch '^.TYPE ' }
    [IO.File]::WriteAllLines($dlg.FileName, $lines, (New-Object Text.UTF8Encoding($true)))   # with a BOM so Excel reads the characters correctly
    Invoke-Item -LiteralPath $dlg.FileName
})
$btnOpen.Add_Click({
    if ($grid.SelectedRows.Count -eq 0) { return }
    $p = [string]$grid.SelectedRows[0].Cells['Path'].Value
    if (Test-Path -LiteralPath $p -PathType Leaf) { Start-Process explorer.exe "/select,`"$p`"" }
    elseif (Test-Path -LiteralPath $p) { Start-Process explorer.exe "`"$p`"" }
    elseif (Test-Path -LiteralPath (Split-Path $p)) { Start-Process explorer.exe "`"$(Split-Path $p)`"" }
    else { [void][System.Windows.Forms.MessageBox]::Show("Not found: $p", 'robocopy') }
})
# Double-clicking a row opens its location too
$grid.Add_CellDoubleClick({ if ($_.RowIndex -ge 0) { $btnOpen.PerformClick() } })
$btnRetry.Add_Click({
    if ($null -eq $script:result) { return }
    $fails = @($script:result.Rows | Where-Object { $_.'Type' -eq 'Failed' })
    if ($fails.Count -eq 0) { [void][System.Windows.Forms.MessageBox]::Show('Nothing failed.', 'robocopy'); return }
    $jobs = [ordered]@{}   # key: source folder|destination folder|options, value: file names ($null = redo the whole folder)
    foreach ($f in $fails) {
        $src = ([string]$f._Src).TrimEnd('\'); $dst = ([string]$f._Dst).TrimEnd('\')
        if (-not $src -or -not $dst) { continue }
        # Carry over only the options that control how files are copied (never /MIR or other deleting options)
        $keep = (@($f._Opt -split '\s+' | Where-Object { $_ -match '^/(COPY:\w+|COPYALL|SEC|DCOPY:\w+|B|ZB|Z|J|EFSRAW|XJ|MT(:\d+)?|IPG:\d+)$' }) -join ' ')
        $p = $f.'Path'.TrimEnd('\')
        if ($p.StartsWith($dst, [StringComparison]::OrdinalIgnoreCase)) { $rel = $p.Remove(0, $dst.Length) }
        elseif ($p.StartsWith($src, [StringComparison]::OrdinalIgnoreCase)) { $rel = $p.Remove(0, $src.Length) }
        else { continue }
        if ($f.'Item' -eq 'Folder') { $jobs["$src$rel|$dst$rel|$keep"] = $null }
        else {
            $relDir = Split-Path $rel; $key = "$src$relDir|$dst$relDir|$keep"
            if (-not $jobs.Contains($key)) { $jobs[$key] = New-Object System.Collections.Generic.List[string] }
            if ($null -ne $jobs[$key]) { $jobs[$key].Add((Split-Path $p -Leaf)) }
        }
    }
    if ($jobs.Count -eq 0) { [void][System.Windows.Forms.MessageBox]::Show('The log does not show the source and destination, so the copy cannot be retried.', 'robocopy'); return }
    $first = @($jobs.Keys)[0] -split '\|'
    $msg = "Copy the {0} failed item(s) again?`r`n`r`nSource: {1}`r`nDestination: {2}`r`n`r`nClose any files that are still open before you click Yes." -f $fails.Count, $first[0], $first[1]
    if ([System.Windows.Forms.MessageBox]::Show($msg, 'robocopy', 'YesNo', 'Question') -ne 'Yes') { return }
    $log = Join-Path (Split-Path $txtPath.Text) ('robocopy-retry_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.log')
    $argList = New-Object System.Collections.Generic.List[string]
    foreach ($k in $jobs.Keys) {
        $s, $d, $o = $k -split '\|'
        if ($null -eq $jobs[$k]) { $names = @('/E') } else { $names = @($jobs[$k] | ForEach-Object { '"' + $_ + '"' }) }
        for ($i = 0; $i -lt $names.Count; $i += 50) {     # 50 files at a time so the command line stays short
            $part = $names[$i..([Math]::Min($i + 49, $names.Count - 1))] -join ' '
            $argList.Add(('"{0}" "{1}" {2} {3} /R:{5} /W:{6} /NP "/UNILOG+:{4}"' -f (Fix-Arg $s), (Fix-Arg $d), $part, $o, $log, [int]$numR.Value, [int]$numW.Value))
        }
    }
    Start-Robo $argList $log -All
})

[void]$form.ShowDialog()

Feel free to use and modify the script. The Japanese text inside it is on purpose: robocopy writes Japanese log lines on Japanese Windows when it runs without a console (more on that below), and the tool needs those words to read such logs.

How to use it

To check a log you already have, drop the log file anywhere on the window (or pick it with Open log...). The items that were still failing are listed at the bottom. If the file is not a robocopy log, the tool says so and leaves the list as it was.

To run a new copy, follow these steps.

  1. Enter the Source and Destination folders, or pick them with Browse.... A share can be entered as \\server\share
  2. Choose How to copy with the check boxes. Left as is, it copies subfolders and retries a failed file up to 2 times, waiting 5 seconds each time
  3. If you copy the same folders every time, click Save current inputs as a set... and give it a name. Next time, pick it under Saved set at the top to fill in the source, destination, log folder, and copy options
  4. Click Run robocopy. The elapsed time is shown while it runs, and Stop ends the run partway. After a stop, the list covers only what ran, and a file that was still being retried is not counted as failed
  5. When it finishes, the window shows what the exit code means, loads the log, and lists what was still failing
  6. Use the Failed, Mismatch, Extra, Skipped, and Copied check boxes to choose which rows to show. The buttons at the bottom save a CSV, open the location, or copy only the failed items again. Double-clicking a row also opens its location
How to copy (on screen) Option added Meaning
Include subfolders /E (/S if Create empty folders too is off) Copies the folders inside as well. On at start
On failure, retry up to … times, waiting … seconds /R:2 /W:5 2 times and 5 seconds at start. Robocopy's default is 1,000,000 retries with a 30-second wait, so one file in use makes the job look stuck
Do not overwrite files that are newer in the destination /XO Keeps a file someone edited in the destination from being replaced by an older version
Mirror /MIR Makes the destination match the source, deleting files that exist only in the destination. The tool asks before it runs
Add more options (advanced) Whatever you type Shows a text box when checked, e.g. /XF *.tmp to exclude files
(always added) /NP and /UNILOG+: No percentage progress in the log, and the log is written as Unicode (UTF-16)

Before you run, the Will run line on the window shows the exact robocopy command your choices make.

The tool with copy options chosen by check boxes. The Will run line shows the matching robocopy options
With Do not overwrite newer files and Add more options (/XF *.tmp) checked, the Will run line changes to /E /R:2 /W:5 /XO /XF *.tmp

You can save as many named sets as you like, and the set you picked last is selected again the next time the window opens. Delete this set removes only the saved set, not any files. Sets are kept in robocopy-failed-list.json in your AppData folder. Mirror is never saved in a set, so it always starts unchecked. If the destination is inside the source, the tool says so instead of running.

Column Contents
Type Failed, Mismatch, Extra, Skipped, or Copied
Item and Path File or folder, and where it is. Extra items show the destination path
Error, Operation, and Log message The error number, what robocopy was doing, and the reason from the log
Likely cause A common cause for that error number, e.g. "still open in Excel" for 32
Attempts and Time How many times that item failed, and when it last failed

List the failures from an older log, e.g. a scheduled job

If Task Scheduler runs robocopy every night, drag that log onto the window or open it with Open log... to get the same list. For an appended log, pick a run under Run. The newest run is selected first, and All runs combined is there too.

The tool after opening an older robocopy log
An appended log from a nightly backup. The list shows what was still failing in the second run

If your nightly robocopy does not write a log yet, add these options. This example runs from PowerShell and creates one log file per day.

robocopy "\\fs01\TeamShare" "E:\Backup\TeamShare" /E /R:2 /W:5 /NP /UNILOG:"E:\Backup\log\backup_$(Get-Date -Format yyyyMMdd).log"

Logs you already have from /LOG or /LOG+ work too, in English or Japanese (on Japanese Windows, which one you get depends on how robocopy is started, more on that below).

Result of a run from the window

The screenshot at the top is a backup of a team share (570 files) run from the tool. I left one Excel quote open, and removed my own read access to one invoice and to the 04_HR folder. When the copy finished, the top showed what the exit code meant, and the list showed two failed files (the quote still open in Excel and the invoice) plus one failed folder (HR), along with the items that exist only in the destination. Below the settings, the tool's counts appear next to the log's own summary.

I also ran it with a share on my NAS (\\nas\share\…) as the destination. The same three items were listed with the same reasons, and copying only the failed items again worked too. With the NAS as the source, the Excel file left open on the NAS showed up as error 32.

Save as CSV and open in Excel opens the rows on screen in Excel, ready to paste into a message asking someone to close a file or asking IT to check a folder's permissions.

The CSV saved by the tool, opened in Excel
The saved CSV in Excel, with path, error number, and likely cause in separate columns

Copy only the failed items again

Once the file is closed, you could run the whole backup again, but on a large share robocopy has to compare every file first. Copy only the failed items again runs robocopy just for the failed files, from the original source to the original destination. For a failed folder, it copies that whole folder again.

It keeps only the options that control how files are copied, such as /COPY: and /COPYALL, from the original run. It never carries over /MIR, /PURGE, or anything else that deletes files in the destination. The retry count and wait time are the ones set on the window. The result goes to robocopy-retry_(date).log in the same folder and is loaded automatically when the copy finishes.

The tool after copying only the failed items again. The invoice and the HR folder, which have no read permission, are still failing
After the Excel quote was closed and the failed items were copied again. The quote copied, and only the two items without permission remain

The exit code this time was 25 (16 + 8 + 1), which includes a fatal error, because the tool could not get into the HR folder at all, so that part of the retry stopped right away. Access denied (error 5) will keep failing no matter how often you retry. Ask the owner of the folder or IT to give the account that runs the backup read permission.

Problems I ran into

The same PC wrote the log in two languages

My PC runs Japanese Windows 11. When I ran robocopy from a PowerShell window, the log was in English. When I ran it without a console window, which is how Task Scheduler runs it, the same robocopy wrote the log in Japanese: "ERROR" became "エラー", and the headings, summary table, and retry lines changed too. A script that searches for "ERROR" in a scheduled job's log would find nothing. If your Windows is not in English, check your scheduled logs. The tool reads both the English and Japanese labels.

/UNILOG+ to a new file was not Unicode

/UNILOG: (overwrite) wrote UTF-16, but /UNILOG+: (append) to a file that did not exist yet wrote 8-bit text. With the console code page set to UTF-8, the Japanese file names and the date in the header were lost. That is why the nightly example above uses /UNILOG: with one file per day. If you want to append, create the file first with only a UTF-16 byte order mark, and /UNILOG+: then appends UTF-16. The tool creates its own logs this way, both for a normal run and for a retry, before it adds /UNILOG+:.

A source folder problem was logged as a destination error

In the test, I removed my own read access to the source folder 04_HR. The log said "Accessing Destination Directory" with the destination path and error 5. Checking the destination's permissions, as the message suggests, would not find the problem. For a folder with error 5, check both the source and destination permissions. The tool's retry treats either path as the same folder.

Summary

  • Searching a robocopy log for "ERROR" also returns retries, files that succeeded on a retry, and earlier runs
  • Drop a log onto the tool, or run robocopy from it, and you get only what was still failing, with reasons and likely causes, ready to save as CSV
  • It can copy only the failed items again. It reads English and Japanese logs from /LOG or /UNILOG, the options are check boxes, and you can save the folders you use often as a named set

My daily NAS backup script is in PowerShell + Robocopy: Daily Backup to a Password-Protected NAS.

References

Comments

Copied title and URL