└── Force-Copy.ps1 /Force-Copy.ps1: -------------------------------------------------------------------------------- 1 | ## .SYNOPSIS 2 | ######################### 3 | ## This script copies a file, ignoring device I/O errors that abort the reading of files in most applications. 4 | ## 5 | ## .DESCRIPTION 6 | ######################### 7 | ## This script will copy the specified file even if it contains unreadable blocks caused by device I/O errors and such. The block that it can not read will be replaced with zeros. The size of the block is determined by the buffer. So, to optimize it for speed, use a large buffer. To optimize for accuracy, use a small buffer, smallest being the cluter size of the partition where your sourcefile resides. 8 | ## 9 | ## .OUTPUTS 10 | ######################### 11 | ## Errorcode 0: Copy operation finished without errors. 12 | ## Errorcode 1: Copy operation finished with unreadable blocks. 13 | ## Errorcode 2: Destination file exists, but -Overwrite not specified. 14 | ## Errorcode 3: Destination file exists but has no bad blocks (i.e. no badblocks.xml file found). 15 | ## Errorcode 4: Destination file can not be written to. 16 | ## 17 | ## .INPUTS 18 | ######################### 19 | ## ... 20 | ## 21 | ## .PARAMETER SourceFilePath 22 | ## Path to the source file. 23 | ## 24 | ## .PARAMETER DestinationFilePath 25 | ## Path to the destination file. 26 | ## 27 | ## .PARAMETER Buffer 28 | ## It makes absolutely no sense to set this less than the cluser size of the partition. Setting it lower than cluster size might force rereading a bad sector in a cluster multiple times. Better is to adjust the retry option. Also, System.IO.FileStream buffers input and output for better performance. (https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream). 29 | ## 30 | ## .EXAMPLE 31 | ## .\Force-Copy.ps1 -SourceFilePath "file_path_on_bad_disk" -DestinationFilePath "destinaton_path" -MaxRetries 6 32 | ## 33 | ## This will copy file_path_on_bad_disk to destinaton_path with maximum of 6 retries on each cluster of 4096 bytes encountered. Usually 6 retries is enough to succeed, unless the sector is really completely unreadable. 34 | ## 35 | ## .EXAMPLE 36 | ## Get-ChildItem '*.jpg' -Recurse -File -Force | foreach {.\Force-Copy.ps1 -SourceFilePath $_.FullName -DestinationFilePath ("C:\Saved"+(Split-Path $_.FullName -NoQualifier)) -Maxretries 2} 37 | ## 38 | ## Get-ChildItem '*.jpg' -Recurse -File -Force | foreach {.\Force-Copy.ps1 -SourceFilePath $_.FullName -DestinationFilePath ("C:\Saved"+(Split-Path $_.FullName -NoQualifier)) -Maxretries 2 -Overwrite} 39 | ## 40 | ## This command will copy all jpg's beginning with "Total" and copy them to "C:\Saved\relative_path" preserving their relative path. 41 | ## When run the second time, the script will only try to reread the bad blocks in the source file, skipping data which was copied well in the previous run. This can be used to efficiently retry reading bad blocks. 42 | ## 43 | ## .EXAMPLE 44 | ## .\Force-Copy.ps1 -SourceFilePath "file_path_on_bad_disk" -DestinationFilePath "destinaton_path" -MaxRetries 6 -Position 1867264 -PositionEnd (1867264+4096) 45 | ## 46 | ## Suppose you have a repairable rar file, which you tried to repair, and it reports that the sector 3647 at offsets 1867264..1871360 can not be repaired. You can still try to read that specific sector with the above command. 47 | ## 48 | ## .EXAMPLE 49 | ## .\Force-Copy.ps1 -SourceFilePath "file_path_on_bad_disk" -DestinationFilePath "destinaton_path" -MaxRetries 6 -BufferSize 33554432 -BufferGranularSize 4096 50 | ## 51 | ## This will quickly copy the file using a 32 MB buffer, and if it encounters an error, it will retry using a 4K buffer (so you get the best of both worlds, performance of a large buffer, and the minimized data loss of a smaller buffer). 52 | ######################### 53 | 54 | [CmdletBinding()] 55 | param( 56 | [Parameter(Mandatory=$true, 57 | ValueFromPipeline=$true, 58 | HelpMessage="Source file path.")] 59 | [string][ValidateScript({Test-Path -LiteralPath $_ -Type Leaf})]$SourceFilePath, 60 | [Parameter(Mandatory=$true, 61 | ValueFromPipeline=$true, 62 | HelpMessage="Destination file path.")] 63 | [string][ValidateScript({Test-Path -LiteralPath $_ -IsValid})]$DestinationFilePath, 64 | [Parameter(Mandatory=$false, 65 | ValueFromPipeline=$false, 66 | HelpMessage="Buffer size in bytes.")] 67 | [int32]$BufferSize=512*2*2*2, # 4096: the default windows cluster size. 68 | [Parameter(Mandatory=$false, 69 | ValueFromPipeline=$false, 70 | HelpMessage="Amount of tries.")] 71 | [int16]$MaxRetries=0, 72 | [Parameter(Mandatory=$false, 73 | ValueFromPipeline=$false, 74 | HelpMessage="Overwrite destination file?")] 75 | [switch]$Overwrite=$false, 76 | [Parameter(Mandatory=$false, 77 | ValueFromPipeline=$true, 78 | HelpMessage="Specify position from which to read block.")] 79 | [int64]$Position=0, # must be 0, current limitation 80 | [Parameter(Mandatory=$false, 81 | ValueFromPipeline=$true, 82 | HelpMessage="Specify end position for reading.")] 83 | [int64]$PositionEnd=-1, # must be -1, current limitation 84 | [Parameter(Mandatory=$false, 85 | ValueFromPipeline=$false, 86 | HelpMessage="Ignore the existing badblocks.xml file?")] 87 | [switch]$IgnoreBadBlocksFile=$false, # not implemented 88 | [Parameter(Mandatory=$false, 89 | ValueFromPipeline=$false, 90 | HelpMessage="Will the source file be deleted in case no bad blocks are encountered?")] 91 | [switch]$DeleteSourceOnSuccess=$false, 92 | [Parameter(Mandatory=$false, 93 | ValueFromPipeline=$false, 94 | HelpMessage="Failback granular buffer size. Set BufferSize to a large value for speed, but revert to using a BufferGranularSize buffer when there is a read error.")] 95 | [int32]$BufferGranularSize=-1, # If > 0, use a larger buffer for speed, and only revert to granular size on an error block. Should be and exact divisor of buffer (BufferSize should be a multiple of BufferGranularSize) 96 | [Parameter(Mandatory=$false, 97 | ValueFromPipeline=$true, 98 | HelpMessage="Write-Progress Bar Parent Id.")] 99 | [int32]$ProgressParentId=-1 100 | ) 101 | 102 | Set-StrictMode -Version 2; 103 | 104 | # Simple assert function from http://poshcode.org/1942 105 | function Assert { 106 | # Example 107 | # set-content C:\test2\Documents\test2 "hi" 108 | # C:\PS>assert { get-item C:\test2\Documents\test2 } "File wasn't created by Set-Content!" 109 | # 110 | [CmdletBinding()] 111 | param( 112 | [Parameter(Position=0,ParameterSetName="Script",Mandatory=$true)] 113 | [ScriptBlock]$condition 114 | , 115 | [Parameter(Position=0,ParameterSetName="Bool",Mandatory=$true)] 116 | [bool]$success 117 | , 118 | [Parameter(Position=1,Mandatory=$true)] 119 | [string]$message 120 | ) 121 | 122 | $message = "ASSERT FAILED: $message" 123 | 124 | if($PSCmdlet.ParameterSetName -eq "Script") { 125 | try { 126 | $ErrorActionPreference = "STOP" 127 | $success = &$condition 128 | } catch { 129 | $success = $false 130 | $message = "$message`nEXCEPTION THROWN: $($_.Exception.GetType().FullName)" 131 | } 132 | } 133 | if(!$success) { 134 | throw $message 135 | } 136 | } 137 | 138 | # Forces read on Stream and returns total number of bytes read into buffer. 139 | function Force-Read() { 140 | param( 141 | [Parameter(Mandatory=$true)] 142 | [System.IO.FileStream]$Stream, 143 | [Parameter(Mandatory=$true)] 144 | [int64]$Position, 145 | [Parameter(Mandatory=$true)] 146 | [ref]$Buffer, 147 | [Parameter(Mandatory=$true)] 148 | [ref]$Successful, 149 | [Parameter(Mandatory=$false)] 150 | [int16]$MaxRetries=0 151 | ) 152 | 153 | $Stream.Position = $Position; 154 | $FailCounter = 0; 155 | $Successful.Value = $false; 156 | 157 | while (-not $Successful.Value) { 158 | 159 | try { 160 | 161 | $ReadLength = $Stream.Read($Buffer.Value, 0, $Buffer.Value.Length); 162 | # If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. (http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx) 163 | 164 | } catch [System.IO.IOException] { 165 | 166 | $ShouldHaveReadSize = [math]::Min([int64] $Buffer.Value.Length, ($Stream.Length - $Stream.Position)); 167 | 168 | if (++$FailCounter -le $MaxRetries) { # Retry to read block 169 | 170 | Write-Host $FailCounter"th retry to read "$ShouldHaveReadSize" bytes starting at "$($Stream.Position)" bytes." -ForegroundColor "DarkYellow"; 171 | Write-Debug "Debugging read retry..."; 172 | 173 | continue; 174 | 175 | } else { # Failed read of block. 176 | 177 | Write-Host "Can not read"$ShouldHaveReadSize" bytes starting at "$($Stream.Position)" bytes: "$($_.Exception.message) -ForegroundColor "DarkRed"; 178 | Write-Debug "Debugging read failure..."; 179 | 180 | # Should be here ONLY on UNsuccessful read! 181 | # $Successful is $false by default; 182 | $Buffer.Value = New-Object System.Byte[] ($Buffer.Value.Length); 183 | return $ShouldHaveReadSize; 184 | 185 | } 186 | 187 | } catch { 188 | 189 | Write-Warning "Unhandled error at $($Stream.position) bit: $($_.Exception.message)"; 190 | Write-Debug "Unhandled error. You should debug."; 191 | 192 | throw $_; 193 | 194 | } 195 | 196 | if ($FailCounter -gt 0) { # There were prior read failures 197 | Write-Host "Successfully read"$ReadLength" bytes starting at "$($SourceStream.Position - $ReadLength)" bytes." -ForegroundColor "DarkGreen"; 198 | } 199 | 200 | # Should be here ONLY on successful read! 201 | $Successful.Value = $true; 202 | # Buffer is allready set during successful read. 203 | return $ReadLength; 204 | 205 | } 206 | 207 | throw "Should not be here..."; 208 | } 209 | 210 | # Returns a custom object for storing bad block data. 211 | function New-Block() { 212 | param ([int64] $OffSet, [int32] $Size) 213 | 214 | $block = new-object PSObject 215 | 216 | Add-Member -InputObject $block -MemberType NoteProperty -Name "OffSet" -Value $OffSet; 217 | Add-Member -InputObject $block -MemberType NoteProperty -Name "Size" -Value $Size; 218 | 219 | return $block; 220 | } 221 | 222 | function Force-Copy-ProgressReport (){ 223 | param ( 224 | [Parameter(Mandatory=$true)] 225 | [int64]$Position, 226 | [Parameter(Mandatory=$true)] 227 | [int64]$PositionEnd, 228 | [Parameter(Mandatory=$true)] 229 | [string] $LatestThroughput, 230 | [Parameter(Mandatory=$true)] 231 | [string] $DetailedStatus 232 | ) 233 | 234 | # Report total percent done 235 | [float] $CurrProgress = $Position/$PositionEnd * 100; 236 | [string] $fName = (Split-Path $SourceFilePath -Leaf) 237 | [string] $fPath = (Split-Path $SourceFilePath -Parent) 238 | Write-Progress -Activity "Force-Copy" -Status "Copying $fName ($LatestThroughput MB/s) from $fPath" -percentComplete ($CurrProgress) -CurrentOperation $DetailedStatus -ParentId $ProgressParentId; 239 | 240 | # Report block being read (only every so often, to avoid flicker and wasted processing) 241 | # Write-Progress -Id 1 -Activity "Force-Copy" -Status $DetailedStatus -percentComplete (-1); 242 | } 243 | 244 | # Snity checks 245 | if ((Test-Path -LiteralPath $DestinationFilePath) -and -not $Overwrite) { 246 | Write-Host "Destination file $DestinationFilePath allready exists and -Overwrite not specified. Exiting." -ForegroundColor "Red"; 247 | exit 2; 248 | } 249 | Assert {$Position -eq 0 -and $PositionEnd -eq -1} "Current limitation: Position and PositionEnd should be 0 and -1 respectively."; 250 | 251 | if ($BufferGranularSize -gt 0) { 252 | Assert {(($BufferSize % $BufferGranularSize) -eq 0) -and ($BufferSize -gt $BufferGranularSize)} "BufferSize must be larger and divisible by BufferGranularSize."; 253 | } 254 | 255 | # Setting global variables 256 | $DestinationFileBadBlocksPath = $DestinationFilePath + '.badblocks.xml'; 257 | $DestinationFileBadBlocks = @(); 258 | 259 | # Fetching SOURCE file 260 | $SourceFile = Get-Item -LiteralPath $SourceFilePath; 261 | Assert {$Position -lt $SourceFile.length} "Specified position out of source file bounds."; 262 | 263 | # Fetching DESTINATION file. 264 | if (-not (Test-Path -LiteralPath ($DestinationParentFilePath = Split-Path -Path $DestinationFilePath -Parent) -PathType Container)) { # Make destination parent folder in case it doesn't exist. 265 | New-Item -ItemType Directory -Path $DestinationParentFilePath | Out-Null; 266 | } 267 | $DestinationFile = New-Object System.IO.FileInfo ($DestinationFilePath); # Does not (!) physicaly make a file. 268 | $NewDestinationFile = -not $DestinationFile.Exists; 269 | 270 | # Special handling for DESTINATION file in case OVERWRITE is used! Only bad block are read from source! 271 | if ($Overwrite -and (Test-Path -LiteralPath $DestinationFilePath)) { 272 | 273 | # Make sure the Source and Destination files have the same length prior to overwrite! 274 | Assert {$SourceFile.Length -eq $DestinationFile.Length} "Source and destination file have not the same size!" 275 | 276 | # Search for badblocks.xml - if it doesn't exist then the file is probably OK, so don't do anything! 277 | if (-not (Test-Path -LiteralPath $DestinationFileBadBlocksPath)) { 278 | 279 | Write-Host "Destination file $DestinationFilePath has no bad blocks. It is unwise to continue... Exiting." -ForegroundColor "Red"; 280 | exit 3; 281 | 282 | } else { # There is a $DestinationFileBadBlocksPath 283 | 284 | $DestinationFileBadBlocks = Import-Clixml $DestinationFileBadBlocksPath; 285 | Write-Host "Badblocks.xml successfully imported. Destination file has $(($DestinationFileBadBlocks | Measure-Object -Sum -Property Size).Sum) bad bytes." -ForegroundColor "Yellow"; 286 | 287 | # Make sure destination file has bad blocks. 288 | if ($DestinationFileBadBlocksPath.Length -eq 0) { 289 | Write-Host "Destination file $DestinationFilePath has no bad blocks according to badblocks.xml. Should not overwrite... Exiting." -ForegroundColor "Red"; 290 | exit 3; 291 | } 292 | 293 | # When using $BufferGranularSize (or other gradual retry logic), it could be writting different size blocks to badblocks file. What would be the implications if it did? 294 | Assert {($DestinationFileBadBlocks | Measure-Object -Average -Property Size).Average -eq $BufferSize } "Block sizes do not match between source and destination file. Can not continue." # This is currently an implementation shortcomming. 295 | 296 | } 297 | } 298 | 299 | # Making buffer 300 | $Buffer = New-Object -TypeName System.Byte[] -ArgumentList $BufferSize; 301 | 302 | # Making container for storing missread offsets. 303 | $UnreadableBlocks = @(); 304 | 305 | # Making filestreams 306 | $SourceStream = $SourceFile.OpenRead(); 307 | $DestinationStream = $DestinationFile.OpenWrite(); 308 | if (-not $?) {exit 4;} 309 | 310 | # Measure time between progress reports to avoid wasting resources (and adding wait times for the UI to redraw) 311 | [TimeSpan] $ReportEvery = New-TimeSpan -Seconds 10; # Wait 10 seconds before first report, then every 3 312 | [TimeSpan] $ReportWaitAfterward = New-TimeSpan -Seconds 3; # Update every 3 seconds after first report 313 | [TimeSpan] $ThroughputRefreshEvery = $ReportEvery - (New-TimeSpan -Seconds 2); # Wait 8+ seconds to recalculate throuput 314 | [Diagnostics.Stopwatch] $sw = [Diagnostics.Stopwatch]::StartNew(); 315 | [TimeSpan] $LatestReportedAt = $sw.Elapsed; 316 | [TimeSpan] $LatestThroughputReportedAt = $LatestReportedAt; 317 | [int64] $InitialPosition = $Position # Remember initial $Position value (before it is changed during iterations) for final throughput calc 318 | [int64] $ThroughputLastPosition = $Position; # Initial position to calculate throughput 319 | [float] $ThroughputLast = 0; # MB/s throughput as of last refresh 320 | [int64] $GranularOverallBadSizeTotal = 0; 321 | 322 | # Measure time between progress reports to avoid wasting resources (and adding wait times for the UI to redraw) 323 | [TimeSpan] $ReportEvery = New-TimeSpan -Seconds 10; # Wait 10 seconds before first report, then every 3 324 | [TimeSpan] $ReportWaitAfterward = New-TimeSpan -Seconds 3; # Update every 3 seconds after first report 325 | [TimeSpan] $ThroughputRefreshEvery = $ReportEvery - (New-TimeSpan -Seconds 2); # Wait 8+ seconds to recalculate throuput 326 | [Diagnostics.Stopwatch] $sw = [Diagnostics.Stopwatch]::StartNew(); 327 | [TimeSpan] $LatestReportedAt = $sw.Elapsed; 328 | [TimeSpan] $LatestThroughputReportedAt = $LatestReportedAt; 329 | [int64] $InitialPosition = $Position # Remember initial $Position value (before it is changed during iterations) for final throughput calc 330 | [int64] $ThroughputLastPosition = $Position; # Initial position to calculate throughput 331 | [float] $ThroughputLast = 0; # MB/s throughput as of last refresh 332 | [int64] $GranularOverallBadSizeTotal = 0; 333 | 334 | if ($PositionEnd -le -1) {$PositionEnd = $SourceStream.Length} 335 | 336 | # Copying starts here 337 | Write-Host "Starting copying of $SourceFilePath..." -ForegroundColor "Green"; 338 | 339 | [bool] $ReadSuccessful = $false; 340 | 341 | while ($Position -lt $PositionEnd) { 342 | 343 | # Report progress so far 344 | # Only report every so often, to avoid flicker and wasted processing/wait times 345 | if( ($LatestReportedAt + $ReportEvery) -le $sw.Elapsed) { 346 | 347 | # Update throughput calculation 348 | if( ($LatestThroughputReportedAt + $ThroughputRefreshEvery) -le $sw.Elapsed) { 349 | $ThroughputLast = [math]::Round(($Position - $ThroughputLastPosition) / 1024 / 1024 / ($sw.Elapsed - $LatestThroughputReportedAt).TotalSeconds, 2); 350 | $LatestThroughputReportedAt = $sw.Elapsed; 351 | $ThroughputLastPosition = $Position; 352 | } 353 | 354 | # Update progress bar(s) 355 | Force-Copy-ProgressReport -Position $Position -PositionEnd $PositionEnd -LatestThroughput $ThroughputLast ` 356 | -DetailedStatus "Reading block ($BufferSize bytes) at position $Position" 357 | 358 | # Update interval variables 359 | $LatestReportedAt = $sw.Elapsed; 360 | $ReportEvery = $ReportWaitAfterward; # Switch to 3 seconds after the initial wait 361 | } 362 | 363 | if ($NewDestinationFile -or 364 | ($PositionMarkedAsBad = $DestinationFileBadBlocks | % {if (($_.Offset -le $Position) -and ($Position -lt ($_.Offset + $_.Size))) {$true;}})) { 365 | 366 | if (($Position -eq 0) -or -not $LastReadFromSource) {Write-Host "Started reading from source file at offset $Position." -ForegroundColor "DarkRed";} 367 | $LastReadFromSource = $true; 368 | 369 | [bool] $GranularLogicUsed = $false; 370 | 371 | # Force read a block from source 372 | if (($BufferGranularSize -gt 0) -and ($MaxRetries -gt 0) ) { 373 | # Try once w/o retries 374 | $ReadLength = Force-Read -Stream $SourceStream -Position $Position -Buffer ([ref] $Buffer) -Successful ([ref] $ReadSuccessful) -MaxRetries 0; 375 | 376 | # If failed, then go again retrying with smaller buffer 377 | if (-not $ReadSuccessful) { 378 | # Granular logic could probably use more testing (extreme cases, like error in last block of file). 379 | # Maybe try and use Holodeck (now open source), see http://stackoverflow.com/questions/4430591/simulating-file-errors-e-g-error-access-denied-on-windows 380 | 381 | # Flag we are switched to smaller buffer (so it doesn't write to output in outer if) 382 | $GranularLogicUsed = $true; 383 | 384 | # Better way to log it, actually granular? Or just ignore the outer buffer size for badblocks purposes (it's unlikely that people will be mixing versions of the script with prior badblock with different sizes) 385 | # $UnreadableBlocks += New-Block -OffSet $Position -Size $ReadLength; 386 | 387 | Write-Host "Switching to granular logic at $Position." -ForegroundColor "DarkGreen"; 388 | 389 | # Allocate granular buffer 390 | $GranularBuffer = New-Object -TypeName System.Byte[] -ArgumentList $BufferGranularSize; 391 | 392 | # Could probably try and refactor with outer loop (and/or refactor conditional), but it could be error prone. For now better duplicate some of the outer loop logic with local variables 393 | # Could also try and do it inside Force-Read (and might be more elegant), but that might have other issues 394 | # Maybe better yet, could refactor into a recursive version, so it would gradually lower the granular buffer size, so it doesn't loose all the speed when it hits an error 395 | [int64] $GranularPosition = $Position; 396 | [int64] $GranularLastPosition = [math]::Min([int64] $Position + $BufferSize, $PositionEnd); 397 | [int64] $GranularReadLength = -1; 398 | [int64] $GranularReadLengthTotal = 0; 399 | [bool] $GranularReadSuccessful = $false; 400 | 401 | while ($GranularPosition -lt $GranularLastPosition) { 402 | # Update progress report 403 | if( ($LatestReportedAt + $ReportEvery) -le $sw.Elapsed) { 404 | if( ($LatestThroughputReportedAt + $ThroughputRefreshEvery) -le $sw.Elapsed) { 405 | $ThroughputLast = [math]::Round(($GranularPosition - $ThroughputLastPosition) / 1024 / 1024 / ($sw.Elapsed - $LatestThroughputReportedAt).TotalSeconds, 2); 406 | $LatestThroughputReportedAt = $sw.Elapsed; 407 | $ThroughputLastPosition = $GranularPosition; 408 | } 409 | 410 | Force-Copy-ProgressReport -Position $GranularPosition -PositionEnd $PositionEnd -LatestThroughput $ThroughputLast ` 411 | -DetailedStatus "Granular reading $BufferGranularSize bytes block at position $GranularPosition" 412 | 413 | $LatestReportedAt = $sw.Elapsed; 414 | $ReportEvery = $ReportWaitAfterward; 415 | } 416 | 417 | $GranularReadLength = Force-Read -Stream $SourceStream -Position $GranularPosition -Buffer ([ref] $GranularBuffer) -Successful ([ref] $GranularReadSuccessful) -MaxRetries ($MaxRetries); 418 | 419 | if (-not $GranularReadSuccessful) { 420 | $GranularOverallBadSizeTotal += $GranularReadLength; 421 | } 422 | 423 | # Here we could log a more granular version of badblocks 424 | $UnreadableBlocks += New-Block -OffSet $GranularPosition -Size $GranularReadLength; 425 | 426 | # Write to destination file. 427 | $DestinationStream.Position = $GranularPosition; 428 | $DestinationStream.Write($GranularBuffer, 0, $GranularReadLength); 429 | 430 | $GranularPosition += $GranularReadLength; 431 | $GranularReadLengthTotal += $GranularReadLength; 432 | } 433 | 434 | $ReadLength = $GranularReadLengthTotal; 435 | 436 | # Does it need an escape clause like $LastReadFromSource (see below) 437 | } 438 | 439 | } else { 440 | 441 | # Original logic w/o granular buffer 442 | $ReadLength = Force-Read -Stream $SourceStream -Position $Position -Buffer ([ref] $Buffer) -Successful ([ref] $ReadSuccessful) -MaxRetries $MaxRetries; 443 | 444 | } 445 | 446 | if (-not $GranularLogicUsed) { 447 | if (-not $ReadSuccessful) { 448 | $UnreadableBlocks += New-Block -OffSet $Position -Size $ReadLength; 449 | } 450 | 451 | # Write to destination file. 452 | $DestinationStream.Position = $Position; 453 | $DestinationStream.Write($Buffer, 0, $ReadLength); 454 | } 455 | 456 | 457 | } else { 458 | 459 | if ($Position -eq 0 -or $LastReadFromSource) {Write-Host "Skipping from offset $Position." -ForegroundColor "DarkGreen";} 460 | $LastReadFromSource = $false; 461 | 462 | # Skipping block. 463 | $ReadLength = $BufferSize; 464 | 465 | } 466 | 467 | $Position += $ReadLength; # adjust position 468 | 469 | } 470 | 471 | $SourceStream.Dispose(); 472 | $DestinationStream.Dispose(); 473 | 474 | $sw.Stop(); 475 | 476 | if ($UnreadableBlocks) { 477 | 478 | # Write summaryamount of bad blocks. 479 | if ($BufferGranularSize -gt 0) { 480 | Write-Host "Up to $GranularOverallBadSizeTotal bytes are bad." -ForegroundColor "Magenta"; 481 | } else { 482 | Write-Host "$(($UnreadableBlocks | Measure-Object -Sum -Property Size).Sum) bytes are bad." -ForegroundColor "Magenta"; 483 | } 484 | 485 | # Export badblocks.xml file. 486 | Export-Clixml -LiteralPath ($DestinationFileBadBlocksPath) -InputObject $UnreadableBlocks; 487 | 488 | } elseif (Test-Path -LiteralPath $DestinationFileBadBlocksPath) { # No unreadable blocks and badblocks.xml exists. 489 | 490 | Remove-Item -LiteralPath $DestinationFileBadBlocksPath; 491 | } 492 | 493 | # Set creation and modification times 494 | $DestinationFile.CreationTimeUtc = $SourceFile.CreationTimeUtc; 495 | $DestinationFile.LastWriteTimeUtc = $SourceFile.LastWriteTimeUtc; 496 | $DestinationFile.IsReadOnly = $SourceFile.IsReadOnly; 497 | 498 | [string] $FinalTimeStr = $sw.Elapsed.ToString(); 499 | [float] $ThroughputMBperS = [math]::Round( ($PositionEnd - $InitialPosition) / 1024 / 1024 / $sw.Elapsed.TotalSeconds, 2); 500 | Write-Host "Copied $PositionEnd bytes in $FinalTimeStr ($ThroughputMBperS MB/s)" -ForegroundColor "Green"; 501 | Write-Host "Finished copying $SourceFilePath!`n" -ForegroundColor "Green"; 502 | 503 | # Return specific code. 504 | if ($UnreadableBlocks) { 505 | exit 1; 506 | } else { 507 | exit 0; 508 | } 509 | --------------------------------------------------------------------------------