Last active
March 26, 2025 04:03
-
-
Save ergosteur/f93f708a35fd15e8f9b70b4def7f4bfa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
[string]$SourceFile = "C:\source\largefile.iso", | |
[string]$TargetFile = "D:\target\largefile.iso" | |
) | |
$contigUrl = "https://download.sysinternals.com/files/Contig.zip" | |
$contigFolder = "$env:TEMP\ContigTool" | |
$contigExe = Join-Path $contigFolder "contig.exe" | |
$contigZip = Join-Path $contigFolder "contig.zip" | |
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 | |
function Ensure-Contig { | |
if (-Not (Test-Path $contigExe)) { | |
Write-Host "Contig.exe not found. Downloading from Sysinternals..." | |
New-Item -ItemType Directory -Path $contigFolder -Force | Out-Null | |
Invoke-WebRequest -Uri $contigUrl -OutFile $contigZip | |
Write-Host "Extracting..." | |
Add-Type -AssemblyName System.IO.Compression.FileSystem | |
[System.IO.Compression.ZipFile]::ExtractToDirectory($contigZip, $contigFolder) | |
if (-Not (Test-Path $contigExe)) { | |
throw "Failed to extract contig.exe" | |
} | |
Write-Host "Contig.exe ready at $contigExe" | |
} else { | |
Write-Host "Contig.exe already available." | |
} | |
} | |
function Get-FileFragmentation { | |
param ( | |
[string]$filePath | |
) | |
Ensure-Contig | |
Write-Host "`nChecking fragmentation for $filePath..." | |
& $contigExe "$filePath" | |
} | |
# Step 1: Preallocate | |
$sourceSize = (Get-Item $SourceFile).Length | |
Write-Host "Preallocating $TargetFile..." | |
fsutil file createnew $TargetFile $sourceSize | |
# Step 2: Sequential copy | |
Write-Host "Copying file data sequentially..." | |
$bufferSize = 1MB | |
$sourceStream = [System.IO.File]::OpenRead($SourceFile) | |
$targetStream = [System.IO.File]::OpenWrite($TargetFile) | |
$buffer = New-Object byte[] $bufferSize | |
do { | |
$read = $sourceStream.Read($buffer, 0, $bufferSize) | |
if ($read -gt 0) { | |
$targetStream.Write($buffer, 0, $read) | |
} | |
} while ($read -gt 0) | |
$sourceStream.Close() | |
$targetStream.Close() | |
Write-Host "Copy complete." | |
# Step 3: Fragmentation check | |
Get-FileFragmentation -filePath $TargetFile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment