SafeCopy

A promise is a promise, here’s my second (planned) application around MD5 hash: a function to copy files and check that the MD5 hash of the copied file is equal to the MD5 hash of the source file.

function SafeCopy ($src,$dest) {
function Check-MD5 ($FilePath) {
$md5=New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash=[System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($FilePath)))
} # EndOf function Check-MD5

$MD5src=Check-MD5 $src
Copy-Item -Path $src -Destination $dest -Force
$MD5dest=Check-MD5 $dest

if (Test-Path $dest)
	{
	if ($MD5dest -match $MD5src)
		{
		Write-Host "`nThe file `"$src`" has been copied in `"$dest`" successfully.`n" -ForegroundColor DarkGreen
		}
	else
		{
		Write-Host "`nThe file `"$src`" has been copied in `"$dest`" but the CRC check failed!`n" -ForegroundColor DarkRed
		}
	}
else
	{
	Write-Host "`nThe file `"$src`" has not been copied in `"$dest`"!`n" -ForegroundColor DarkRed
	}
} # EndOf function SafeCopy

Leave a Reply

Scroll to Top